根据同一个表中的不同条件显示相同字段的计数

时间:2011-05-06 14:28:36

标签: sql pivot

假设我的表格只有两个字段:Idcolor

id  color
----------
1   Green
2   Red
3   Yellow

我希望计数显示在不在列中的行中。

  SELECT COUNT(color), color
    FROM MYTABLE
GROUP BY color

这给了我:

count   color
--------------
10      Green
20      Red
15      Yellow

我需要它显示为:

Green  Red  Yellow
-------------------
10     20   15

4 个答案:

答案 0 :(得分:3)

SELECT
  COUNT(CASE Color WHEN 'Green'  THEN 1 END) AS Green,
  COUNT(CASE Color WHEN 'Red'    THEN 1 END) AS Red,
  COUNT(CASE Color WHEN 'Yellow' THEN 1 END) AS Yellow
FROM MYTABLE

您不需要在此处进行分组。基本上,每个COUNT传递所有行,但计数Color匹配特定值的那些。

答案 1 :(得分:1)

select (select COUNT(color) from MyTable where color='Green') as 'Green', 
       (select COUNT(color) from MyTable where color='Red') as 'Red'. 
       (select COUNT(color) from MyTable where color='Yellow') as 'Yellow'

答案 2 :(得分:1)

另一种方法(仅限MySQL 中的)是:

SELECT SUM(color = 'Green')  AS "Green"
     , SUM(color = 'Red')    AS "Red"
     , SUM(color = 'Yellow') AS "Yellow"
FROM MyTable ;

答案 3 :(得分:0)

试试此链接http://blog.programmingsolution.net/sql-server-2008/sql-server-pivot-converting-rows-to-columns-with-dynamic-query/

但是如果你做这样的事情

 select [ID],[COLOUR] from

 ( SELECT [ID],[COLOUR] FROM [dbo].[table] ) as S

 Pivot ( COUNT([COLOUR])

 FOR COLOUR IN ([YELLOW],[RED],[GREEN])

 ) as P