我有一个包含三个字段的表:。
field1 - field2 - field3
field1是id;
field2是日期;
field3只有两种可能 值(" ac"和" re")。
我需要知道是否可以使用group by
来查询最终显示的结果:
select field2
, count(total per date)
, Count(where field3 = "re")
from myTable
group by 1;
如果我的表是:
field1 - field2 - field3
=========================
item1 - date1 - "ac"
item2 - date1 - "re"
item3 - date1 - "re"
item4 - date2 - "re"
item5 - date2 - "ac"
item6 - date3 - "ac"
结果如下:
- date1 - 3 - 2
- date2 - 2 - 1
- date3 - 1 - 0
答案 0 :(得分:1)
SELECT field2, COUNT(*), SUM(CASE WHEN field3='re' THEN 1 ELSE 0 END) as re_count
FROM table1
GROUP BY field2
答案 1 :(得分:0)
您可以将条件sum
与case
语句一起使用:
select field2
, count(field3)
, sum(case when field3 = 're' then 1 else 0 end)
from myTable
group by field2
甚至更短,使用if
:
select field2
, count(field3)
, sum(if(field3 = 're', 1, 0))
from myTable
group by field2
或只是:
select field2
, count(field3)
, sum(field3 = 're')
from myTable
group by field2