DATEPART缺少月份

时间:2018-11-02 19:02:10

标签: sql-server

晚上好,请帮我进行以下查询(sqlserver):

<!-- @[/Hero] -->

结果是这样的:

SELECT
DATEPART (YEAR, spese_generali.data) as 'YEAR',
DATEPART (MONTH, spese_generali.data) as 'MONTH',
SUM (spese_generali.importo) as amount
FROM spese_generali 
group by DATEPART (MONTH, spese_generali.data), 
         DATEPART (YEAR,spese_generali.data) 
order by 'YEAR'

我希望结果是这样的:

YEAR   MONTH  amount
2017   6      296.00
2018   1      131.00
2018   2      154.00
2018   3      441.00
etc.

也就是说,对于丢失的月份,您必须输入0作为收款额

1 个答案:

答案 0 :(得分:1)

如果您没有日历表,则可以轻松地制作一个日历表。类似于以下内容:

DECLARE 
    @beg_date DATE = '2017-06-01',
    @end_date DATE = '2018-11-01';

WITH 
    cte_n1 (n) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) n (n)), 
    cte_n2 (n) AS (SELECT 1 FROM cte_n1 a CROSS JOIN cte_n1 b),
    cte_Calendar (d) AS (
        SELECT TOP (DATEDIFF(MONTH, @beg_date, @end_date) + 1)
            DATEADD(MONTH, ROW_NUMBER() OVER (ORDER BY a.n) -1, @beg_date)
        FROM
            cte_n2 a CROSS JOIN cte_n2 b
        )

SELECT
    YEAR = DATEPART(YEAR, c.d),
    MONTH = DATEPART(MONTH, c.d),
    amount = SUM(sg.importo)
FROM
    cte_Calendar c
    LEFT JOIN dbo.spese_generali sg
        ON sg.date >= c.d
        AND sg.date < DATEADD(MONTH, 1, c.d)
GROUP BY
    DATEPART(MONTH, c.d),
    DATEPART(YEAR, c.d)
ORDER BY
    'YEAR';