我想采用以下声明并将其融合到一个查询中。
SELECT COUNT(*) AS count1 WHERE Month='11' AND Flag = 1
SELECT COUNT(*) AS count2 WHERE Month='11' AND Flag = 2
SELECT COUNT(*) AS count1 WHERE Month='12' AND Flag = 1
SELECT COUNT(*) AS count2 WHERE Month='12' AND Flag = 2
我希望这显示为一个查询,其中包含列count1和count2以及第11行和第12个月的行。
有这个语法吗?
答案 0 :(得分:6)
您可以将SUM
和CASE
结合使用,一次性获取各种计数:
SELECT
Month,
SUM(CASE WHEN Flag=1 THEN 1 ELSE 0 END) as count1,
SUM(CASE WHEN Flag=2 THEN 1 ELSE 0 END) as count2
from
...
WHERE Month in ('11','12')
GROUP BY
Month /* Other columns? */
答案 1 :(得分:1)
只有两列,它可以是这样的:
select
(SELECT COUNT(*) FROM tablename WHERE Month='11' AND Flag = 1) as 'count1'
(SELECT COUNT(*) FROM tablename WHERE Month='11' AND Flag = 2) as 'count2'
UNION ALL
select
(SELECT COUNT(*) FROM tablename WHERE Month='12' AND Flag = 1),
(SELECT COUNT(*) FROM tablename WHERE Month='12' AND Flag = 2)
将tablename
替换为您的表名。
答案 2 :(得分:-1)
这个怎么样:
select
month, flag, count(*)
from
table
where
month in ('11', '12') and
flag in (1, 2)
group by
month, flag;