5

我想采用以下语句并将其融合到一个查询中。

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 个月的行。

有没有这样的语法?

4

3 回答 3

9

您可以一次组合SUMCASE获得各种计数:

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? */
于 2012-06-06T14:20:48.163 回答
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为您的表的名称。

于 2012-06-06T14:20:18.990 回答
-1

这个怎么样:

select
    month, flag, count(*)
from
    table
where
    month in ('11', '12') and
    flag in (1, 2)
group by
    month, flag;
于 2012-06-06T14:19:33.487 回答