SQL:Count,Sum和Group by

时间:2016-05-25 21:24:21

标签: sql count group-by sum

我查询数据库:

ID    Date1       Date2        Status  FK
1    12-05-2016  20-05-2016    ok       3
2    24-05-2016  27-05-2016    NOK      3
3    29-05-2016  06-06-2016    OK       4

我需要按日期(date1或date2)和fk进行总和分组。

这样的事情:

Month        Sum        FK
5            2          3
5            1          4
6            1          4

我试过这个,但它没有给我我的期望

select Month(date1)as date1 ,MONTH(date2) as date2 ,COUNT(*) as sum, fk
from table
where status ='OK'
group by fk , MONTH(date1), MONTH(date2);

提前致谢!

1 个答案:

答案 0 :(得分:1)

试试这个:

select sum(sm),fk,dt from 
(
select Month(date1)as dt ,COUNT(*) as sm, fk

from table

where status ='OK'

group by fk , MONTH(date1)

union all
select Month(date2)as dt ,COUNT(*) as sm, fk

from table

where status ='OK'

group by fk , MONTH(date2)

)
group by dt,fk