如何在SQL查询中不存在现有记录

时间:2016-05-13 05:26:22

标签: sql sql-server sql-server-2008

我得到以下正确的结果,我需要记录 07/06/2015 0介于吼叫之间。我在Row数据绑定和SQL查询中也进行了一些试验。但没有任何线索。

我的查询

SELECT
    CONVERT(nvarchar(15), TransDate, 103) billdate,
    ISNULL(SUM(CONVERT(int, Amount)), '0') Amount
FROM HMS_DiagnosisTransactions
WHERE
    TransDate BETWEEN '2015-06-06 00:00:00.000' AND '2015-06-09 00:00:00.000'
GROUP BY
    CONVERT(nvarchar(15), TransDate, 103),
    status,
    CAST(TransDate AS date)
ORDER BY CAST(TransDate AS date)

结果

Result

2 个答案:

答案 0 :(得分:3)

试试这个

;WITH dates AS 
(
    SELECT CONVERT(date,'2015-06-06 00:00:00.000') as Date
    UNION ALL
    SELECT DATEADD(d,1,[Date])
    FROM dates 
    WHERE DATE < '2015-06-09 00:00:00.000'
)
select CONVERT(nvarchar(15), d.date, 103) billdate,
    ISNULL(SUM(CONVERT(int, hd.Amount)), '0') Amount from dates d
left join HMS_DiagnosisTransactions hd on convert(date,d.date) = convert(date,hd.TransDate)         
GROUP BY
    CONVERT(nvarchar(15), d.date, 103),
    hd.status,
    CAST(d.date AS date)
ORDER BY CAST(d.date AS date)
OPTION (MAXRECURSION 100)

答案 1 :(得分:1)

我建议创建一个主表格,存储您要显示的所有账单日期。

CREATE TABLE MasterDate 
(
    mDate nvarchar(15)
)
GO

添加适当的条目,例如

INSERT INTO MasterDate (mDate) VALUES ('06/06/2015');
INSERT INTO MasterDate (mDate) VALUES ('07/06/2015');
INSERT INTO MasterDate (mDate) VALUES ('08/06/2015');
GO

然后将此主表加入您的

SELECT
    m.mDate AS billdate,
    isnull(t.Amount, 0)
FROM
    MasterDate m 
LEFT JOIN 
(
    SELECT CONVERT(nvarchar(15), TransDate, 103) billdate, ISNULL(SUM(CONVERT(int, Amount)), '0') Amount
    FROM HMS_DiagnosisTransactions
    WHERE TransDate BETWEEN '2015-06-06 00:00:00.000' AND '2015-06-09 00:00:00.000'
    GROUP BY CONVERT(nvarchar(15), TransDate, 103), status, CAST(TransDate AS date)
    ORDER BY CAST(TransDate AS date)
) t ON m.mDate = t.billdate

使用此所有帐单日期将显示行。如果您的结果中没有条目,则AmountLEFT JOIN而后应为空,后来显示为0 ISNULL功能。希望这会有所帮助。