我有一个SQL查询,如下所示:
SELECT
R.BOOK_YM, COUNT(*)
FROM
#TB_TRANSED_GUI_AMOUNT AS R
GROUP
BY R.BOOK_YM
所选结果如下:
BOOK_YM | count(*)
---------+---------
201411 | 51
201412 | 142
201501 | 1
201506 | 1
如何修改结果如下:
BOOK_YM | count(*)
--------+-----------
201411 | 51
201412 | 142
201501 | 1
201502 | 0
201503 | 0
201504 | 0
201505 | 0
201506 | 1
答案 0 :(得分:0)
您可以使用以下内容获取2个日期之间所有YYYYMM的表格,并在联接中使用生成的@YMList变量:
declare @StartDate date = cast(dateadd(month, -12, GetDate()) as date)
declare @EndDate date = cast(GetDate() as date)
declare @YMList TABLE (YYYYMM INT)
;with dates as (
SELECT cast(@StartDate as Date) [date]
UNION ALL
SELECT DATEADD(month,1,t.date)
FROM dates t
WHERE t.[date] < @EndDate
)
insert @YMList (YYYYMM)
select
YEAR([Date]) * 100 + MONTH([Date]) AS YYYYMM
from dates
WHERE [Date] < @EndDate
OPTION (MAXRECURSION 10000)
答案 1 :(得分:0)
试试这个:(我认为BOOK_YM
是varchar
字段,如果不是CAST
它
SELECT
Y.YYYY + M.MM AS BOOK_YM,
COUNT(R.BOOK_YM) AS CNT
FROM
(SELECT SUBSTRING(BOOK_YM, 1, 4) As YYYY
FROM t
GROUP BY SUBSTRING(BOOK_YM, 1, 4)) AS Y
CROSS JOIN
(SELECT '01' As MM
UNION ALL SELECT '02'
UNION ALL SELECT '03'
UNION ALL SELECT '04'
UNION ALL SELECT '05'
UNION ALL SELECT '06'
UNION ALL SELECT '07'
UNION ALL SELECT '08'
UNION ALL SELECT '09'
UNION ALL SELECT '10'
UNION ALL SELECT '11'
UNION ALL SELECT '12') AS M
LEFT JOIN
t AS R
ON Y.YYYY + M.MM = R.BOOK_YM
WHERE
Y.YYYY + M.MM BETWEEN (SELECT MIN(BOOK_YM) FROM t) AND (SELECT MAX(BOOK_YM) FROM t)
GROUP BY
Y.YYYY + M.MM