如何在一列中选择COUNT个多个值

时间:2014-02-26 18:18:46

标签: sql sql-server

而不是SQL的新手,所以请保持温和......因为我认为这是一个基本的。

我正在尝试根据Column1编写一个包含多个(13)计数的查询。第一计数是总计。然后其他12个用Color过滤。我可以通过在一个查询中执行多个计数来获得我的结果,但这给了我13行数据。这里的目标是将所有内容都放在一行上。所以,几乎每个计数都是它自己的列。以下是数据模型的示例

Database = CARS, Table = TYPES, Column1 = LICENSE, Column2 = COLOR

SELECT COUNT (LICENSE) AS 'Total ALL Cars'
FROM CARS.TYPES WITH (NOLOCK)

SELECT COUNT (LICENSE) AS 'Total RED Cars'
FROM CARS.TYPES WITH (NOLOCK)
WHERE COLOR = 'RED'

并且& on&每种剩余的颜色。这是有效的,但同样,我试图将其全部简化为一行数据,如果可能的话。提前谢谢

4 个答案:

答案 0 :(得分:9)

您只需要在select语句中包含颜色并按其分组以计算每种颜色的汽车。

 SELECT Color, Count(*)
 FROM CARS.TYPES WITH(NOLOCK)
 GROUP BY Color

SELECT COUNT(CASE WHEN Color = 'RED' THEN 1
                  ELSE NULL
             END) AS RedCars
       ,COUNT(CASE WHEN Color = 'BLUE' THEN 1
                   ELSE NULL
              END) AS BlueCars
       ,COUNT(*) AS AllCars
    FROM CARS.TYPES WITH ( NOLOCK )

答案 1 :(得分:6)

您可以使用条件SUM()

执行此操作
SELECT SUM(CASE WHEN Color = 'Red' THEN 1 END) AS 'Total Red Cars'
      ,SUM(CASE WHEN Color = 'Blue' THEN 1 END) AS 'Total Blue Cars'
FROM CARS.TYPES

如果使用MySQL,您可以进一步简化:

SELECT SUM(Color = 'Red') AS 'Total Red Cars'
      ,SUM(Color = 'Blue') AS 'Total Blue Cars'
FROM CARS.TYPES

答案 2 :(得分:4)

PIVOT

SELECT RED + BLUE + GREEN AS total,
       RED,
       BLUE,
       GREEN
FROM   CARS.TYPES PIVOT (COUNT (LICENSE) FOR COLOR IN ([RED], [BLUE], [GREEN])) P 

答案 3 :(得分:0)

 SELECT SUM(Al) AllCount, SUM(Red) RedCount, SUM(Green) GreenCount, ...
 (  
   SELECT 1 AS Al 
   , CASE WHEN Color = 'Red' THEN 1 ELSE 0 END AS Red 
   , CASE WHEN Color = 'Green' THEN 1 ELSE 0 END AS Green
   ... 
   FROM CARS.Types
 )