在同一个select语句中聚合查询

时间:2012-02-08 18:34:07

标签: sql-server aggregates

我有一个select语句,它返回5列(需要1-2分钟) 其中一列是颜色(即只有红色,蓝色和黄色三种颜色)。现在我想在同一个select语句中显示具有Red的行数,具有Blue的行数和具有黄色的行数。

Select语句是这个

enter image description here

我想要像这样输出

enter image description here

任何帮助?

2 个答案:

答案 0 :(得分:1)

你想要这个(对于SQL Server 2005 +):

SELECT  *, SUM(CASE WHEN Color = 'RED' THEN 1 ELSE 0 END) OVER() [RED],
        SUM(CASE WHEN Color = 'BLUE' THEN 1 ELSE 0 END) OVER() [BLUE],
        SUM(CASE WHEN Color = 'Yellow' THEN 1 ELSE 0 END) OVER() [Yellow]
FROM YourTable

答案 1 :(得分:1)

使用CTE(公用表格表达式):

; 
WITH cte AS
( SELECT ...
  ... your query here
) 
WITH grp AS
( SELECT 
        color
      , COUNT(*) AS cnt
  FROM
        cte
  GROUP BY
        color
) 
SELECT 
      cte.*
    , (SELECT cnt FROM grp WHERE color = 'Red')    AS Red
    , (SELECT cnt FROM grp WHERE color = 'Blue')   AS Blue
    , (SELECT cnt FROM grp WHERE color = 'Yellow') AS Yellow
FROM 
      cte