如何显示没有余额的SQL Server的每月余额

时间:2018-11-29 23:58:20

标签: sql-server

我有以下代码块,用于查询SQL Server数据库,该数据库汇总了过去13个月中每个月的所有余额。它工作得很好,但是有几个月没有余额要报告。这些个月没有显示我需要的。在这一点上,我不知所措。

DECLARE @StartDate DATE, @EndDate DATE;

SELECT 
    @StartDate = CONVERT(VARCHAR(11), DATEADD(month, -13, GETDATE())),
    @EndDate = CONVERT(VARCHAR(11), DATEADD(month, 0, GETDATE()));

;WITH d(d) AS
(
    SELECT 
        DATEADD(MONTH, n, DATEADD(MONTH, DATEDIFF(MONTH, 0, @StartDate), 0))
    FROM 
        (SELECT TOP (DATEDIFF(MONTH, @StartDate, @EndDate) + 1)
             n = ROW_NUMBER() OVER (ORDER BY [object_id]) - 1
         FROM 
             sys.all_objects ORDER BY [object_id]) AS n
)
SELECT
    FORMAT(d.d, 'MMM yy') AS Purchase_Date,
    CAST(ROUND(SUM(lm.BALANCE), 0) AS FLOAT) AS Balance
FROM 
    d 
LEFT OUTER JOIN 
    dbo.purchases AS lm ON lm.purchase_date >= d.d
                        AND lm.purchase_date < DATEADD(MONTH, 1, d.d)
WHERE 
    lm.Buyer_code = 'FirstTime'
    AND lm.PROGRAM_ID = 'NewBuyers'
GROUP BY 
    d.d
ORDER BY 
    d.d

1 个答案:

答案 0 :(得分:2)

您正在用where子句覆盖LEFT JOIN,这要求每一行都必须具有来自左联接表的某些值。实际上,它等效于内部联接。您需要允许d中的行保留到结果中,您可以通过直接在LEFT JOIN中使用所需条件来做到这一点:

SELECT
    FORMAT( d.d, 'MMM yy' )                        AS Purchase_Date
  , CAST( ROUND( SUM( lm.BALANCE ), 0 ) AS float ) AS Balance
FROM d
LEFT OUTER JOIN DBO.purchases AS lm ON lm.purchase_date >= d.d
    AND lm.purchase_date < DATEADD( MONTH, 1, d.d )
    AND lm.Buyer_code = 'FirstTime'
    AND lm.PROGRAM_ID = 'NewBuyers
GROUP BY
    d.d
ORDER BY
    d.d