SQL - Case When (統計資料)

  • 1293
  • 0
  • SQL
  • 2015-03-25

摘要:SQL - Case When (統計資料)

今天好巧不巧的在網路上找到一篇以前發問的文章,問題是關於資料表內的資料統計

乾脆就順便回收回自己的部落格好了,需求如下,我希望能將資料表的資料(圖一)統計

為(圖二)

 

【原始資料】

SELECT * INTO #TEMP FROM

(SELECT '小說' AS 類別,'笑傲江湖' AS 書名,'N' AS 閱讀狀態,'Y' AS 我的最愛
UNION
SELECT '小說' AS 類別,'鹿鼎記' AS 書名,'Y' AS 閱讀狀態,'N' AS 我的最愛
UNION
SELECT '小說' AS 類別,'碧血劍' AS 書名,'Y' AS 閱讀狀態,'N' AS 我的最愛
UNION
SELECT '小說' AS 類別,'書劍恩仇錄' AS 書名,'Y' AS 閱讀狀態,'N' AS 我的最愛) A

 

 

【解決方式(Solution)】

SELECT 類別,
Count(*) AS 總筆數,Sum(CASE WHEN 3 = 'Y' THEN 1 ELSE 0 END) AS 已閱讀完筆數,
Sum(CASE WHEN 4 = 'Y' THEN 1 ELSE 0 END) AS 喜愛筆數
FROM #temp
GROUP BY 類別;

 

 

利用case when + sum 這種小技巧就達到如此的效用,又是江湖一點訣,說破不值錢。