一張激活表TL_CSU_ACTIVATE_LOG:
一張用戶表TV_CSU_USER
現在要查詢2014-12to2015-12每月注冊的不同類型(T,B,M,D)用戶數,如下圖:
sql 應該怎麼寫
參考Oracle行列轉換
因為你的類型是固定的,所以直接查詢,如果你的類型不固定,可以參考上面的鏈接。
SELECT TT.Month
,SUM(CASE WHEN TT.TYPE = 'B' THEN Count ELSE 0 END) AS B
,SUM(CASE WHEN TT.TYPE = 'M' THEN Count ELSE 0 END) AS M
,SUM(CASE WHEN TT.TYPE = 'D' THEN Count ELSE 0 END) AS D
,SUM(CASE WHEN TT.TYPE = 'T' THEN Count ELSE 0 END) AS T
FROM (
SELECT TO_CHAR(T1.ACTIVATE_TIME, 'yyyy-MM') AS Month
, T2.TYPE
, COUNT(*) AS Count
FROM TL_CSU_ACTIVATE_LOG T1
LEFT JOIN TV_CSU_USER T2 ON T2.USER_ID = T1.USER_ID
WHERE TO_CHAR(T1.ACTIVATE_TIME, 'yyyy-MM') >= '2014-12' AND TO_CHAR(T1.ACTIVATE_TIME, 'yyyy-MM') <= '2015-12'
GROUP BY T2.TYPE
) TT
GROUP BY TT.Month
ORDER BY TT.Month