在SQL

2016-03-07 75 views
0
在計算行使用金額

我有這樣的代碼,運行時應該返回出租車酒店和食品總數的計數:在SQL

SELECT 
    COUNT(CASE WHEN [TaxiHotelFood] LIKE '%Taxi%' THEN 1 END) AS "Taxis", 
    COUNT(CASE WHEN [TaxiHotelFood] LIKE '%Hotel%' THEN 1 END) AS "Hotel", 
    COUNT(CASE WHEN [TaxiHotelFood] LIKE '%Taxi%' THEN 1 END) AS "Food" 
    FROM [CSART].[dbo].[tblPatAdmission] 
    WHERE (TaxiHotelFood != '' AND TaxiHotelFood IS NOT NULL) 
    GROUP BY TaxiHotelFood 

相反,它返回的是這樣的:

Taxis Hotel Food 
0   2  0 
1   1  1 

它不會添加計數,除非該字段的內容相同。有沒有簡單的方法來解決這個問題?

+2

您能提供樣品數據和預期結果嗎?我沒有看到你的查詢有什麼問題。當你說'添加計數'時,你的意思是你只需要一行作爲結果(1,3,1)?如果是這樣,放棄'組'... – sgeddes

+0

哇,真的不應該花了我一個多小時才弄清楚。謝謝,它現在正在工作。 – user1834616

+0

您是否注意到第二個'%Taxi%'應該是'%Food%'? –

回答

0
SELECT 
COUNT(CASE WHEN [TaxiHotelFood] LIKE '%Taxi%' THEN 1 END) AS "Taxis", 
COUNT(CASE WHEN [TaxiHotelFood] LIKE '%Hotel%' THEN 1 END) AS "Hotel", 
COUNT(CASE WHEN [TaxiHotelFood] LIKE '%Taxi%' THEN 1 END) AS "Food" 
FROM [CSART].[dbo].[tblPatAdmission] 
WHERE (TaxiHotelFood != '' AND TaxiHotelFood IS NOT NULL) 
GROUP BY TaxiHotelFood 
UNION 
SELECT 
SUM(CASE WHEN [TaxiHotelFood] LIKE '%Taxi%' THEN 1 END) AS "Taxis", 
SUM(CASE WHEN [TaxiHotelFood] LIKE '%Hotel%' THEN 1 END) AS "Hotel", 
SUM(CASE WHEN [TaxiHotelFood] LIKE '%Taxi%' THEN 1 END) AS "Food" 
FROM [CSART].[dbo].[tblPatAdmission] 
WHERE (TaxiHotelFood != '' AND TaxiHotelFood IS NOT NULL) 
GROUP BY TaxiHotelFood