假设我的表格只有两个字段:Id
和color
。
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
答案 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)
但是如果你做这样的事情
select [ID],[COLOUR] from
( SELECT [ID],[COLOUR] FROM [dbo].[table] ) as S
Pivot ( COUNT([COLOUR])
FOR COLOUR IN ([YELLOW],[RED],[GREEN])
) as P