如何选择一个特定的值并将其连接到第一个结果集

m3eecexj  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(309)

我有一个select语句,它从表中返回几列。我有一个“daysince”列(第3个),实际上是一个日期差异。
我需要再选择一列(作为numberofrecord),它将表示具有相同“daysince”值的行数。我只是在这里添加了数字7来解释结构的外观,即使该列的正确值是:
对于daysince val介于10和14之间的行,为1
自val 15起有一天的行为8
从val 16开始有一天的行为2
希望我的要求有道理。我试图运行一些随机左,右,全外连接与可怕的结果。有人能用正确的方式称呼我吗?
下面是示例查询

SELECT username, id, DATEDIFF( creation, '2018/02/28') as daySince, 7 as numberOfRecord
FROM MyTable 
ORDER BY daySince ASC
username  id daySince numberOfRecord
rob 2D8836  11  7
rob 2D8836  12  7
rob 2D8836  13  7
rob 2D8836  14  7
rob 2D8836  15  7
rob 2D8836  15  7
rob 2D8836  15  7
rob 2D8836  15  7
rob 2D8836  15  7
rob 2D8836  15  7
rob 2D8836  15  7
rob 2D8836  15  7
rob 2D8836  16  7
rob 2D8836  16  7
zysjyyx4

zysjyyx41#

根据你想要的,你要么通过 username, id :

SELECT username, id, DATEDIFF(creation, '2018-02-28') as daySince, COUNT(*)
FROM MyTable 
GROUP BY username, id, DATEDIFF( creation, '2018-02-28')
ORDER BY daySince ASC;

或者你应该移除 username 以及 id ,因为它们是不相关的:

SELECT DATEDIFF(creation, '2018-02-28') as daySince, COUNT(*)
FROM MyTable 
GROUP BY DATEDIFF( creation, '2018-02-28')
ORDER BY daySince ASC;
pod7payv

pod7payv2#

看看这个。

SELECT
            username, id, 
            DATEDIFF( creation, '2018/02/28') as daySince, 
            Count(DATEDIFF( creation, '2018/02/28')) as numberOfRecord
        FROM MyTable 
        Group By DATEDIFF( creation, '2018/02/28')
        ORDER BY daySince ASC

相关问题