我想计算一个分组之后的特定列,但结果与我的预期不同。情况就是这样:假设我有一张包含这些数据的表格:
sdate name collected
2017-01-01 John 5
2017-01-01 John 3
2017-01-01 Wick 6
2017-01-01 Wick 6
2017-01-02 Mary 5
2017-01-02 Pete 1
2017-01-02 Mary 4
2017-01-02 Pete 2
2017-01-03 John 8
我希望使用以下查询获得collected
的总和:
select name, sdate, sum(collected) as count from test
group by name, sdate
order by sdate
输出:
sdate name count
2017-01-01 wick 9
2017-01-01 john 11
2017-01-02 pete 3
2017-01-02 mary 9
2017-01-03 john 8
问题:我想从上面的结果中select count(name) group by sdate
,结果将是:
sdate name count countName
2017-01-01 wick 9 2
2017-01-01 john 11 2
2017-01-02 pete 3 2
2017-01-02 mary 9 2
2017-01-03 john 8 1
如何实现这一目标?我试着用下面的声明做这件事:
select A.*, count(A.name) as countName
from
(select sdate, name, sum(collected) as count from test
group by name, sdate
order by sdate) A
group by A.sdate
输出:
sdate name count countName
2017-01-01 wick 9 2
2017-01-02 mary 9 2
2017-01-03 john 8 1
计数是正确的,但行数将被分组,这是我不想要的。知道如何在不删除行的情况下实现它吗?
答案 0 :(得分:2)
目前还不是很清楚你想要什么,但似乎你想知道每组中有多少行。将count(*) as countName
添加到原始查询中:
select name, sdate, sum(collected) as count, count(*) as countName
from test
group by name, sdate
order by sdate
答案 1 :(得分:0)
试试这个:
select name, sdate, sum(collected) as count, count(*) as countName
from test
group by name, sdate
order by sdate;