建立表 sql
CREATE TABLE [dbo].[color]( [id] [int] IDENTITY(1,1) NOT NULL, [color] [varchar](50) NULL ) ON [PRIMARY]
隨機插入數據 spa
id | color |
1 | green |
2 | red |
3 | blue |
4 | green |
5 | red |
6 | red |
統計每種 顏色的數量 code
當須要使用一個語句查詢每種顏色的數量時,不能把顏色條件放進WHERE條件中, 由於每種顏色是互斥的。 ci
red | blue |
green |
3 |
1 |
2 |
下面SQL可獲得上面的結果: table
SELECT SUM(CASE WHEN(color = 'red') THEN 1 END) AS red, SUM(CASE WHEN(color = 'blue') THEN 1 END) AS blue, SUM(CASE WHEN(color = 'green') THEN 1 END) AS green FROM [dbo].[color]
或者 class
SELECT COUNT(CASE WHEN(color = 'red') THEN 1 END) AS red, COUNT(CASE WHEN(color = 'blue') THEN 1 END) AS blue, COUNT(CASE WHEN(color = 'green') THEN 1 END) AS green FROM [dbo].[color]