强制查询返回所有范围,即使没有数据也是如此

时间:2019-03-18 01:26:30

标签: sql tsql case

我有一个查询,该查询会计算3个总和,然后将其分类为迟到的付款范围。

但是有时某些范围内没有数据,因此查询返回的行少于3行。

即使没有特定DaysLate范围的数据,如何强制查询始终返回3行?在这种情况下,SumaDocs应当包含零。

SELECT MIN(b.Range) Nazwa, SUM(b.Remaining) Suma, COUNT(*) Docs
FROM (
SELECT
CASE
    WHEN a.DaysLate BETWEEN 1 AND 14 THEN 'Late 1 to 14 days'
    WHEN a.DaysLate BETWEEN 15 AND 30 THEN 'Late 15 to 30 day'
    ELSE 'Late over 30 days'
END AS Range,
CASE
    WHEN a.DaysLate BETWEEN 1 AND 14 THEN 1
    WHEN a.DaysLate BETWEEN 15 AND 30 THEN 2
    ELSE 3
END AS Order,
Remaining, DaysLate
FROM (
    SELECT DATEDIFF(dd, PaymentDate, GETDATE()) DaysLate, (WN - MA) Remaining
    FROM dbo.MyData
    WHERE DATEDIFF(dd, PaymentDate, GETDATE()) > 0 AND KOD_ID = @KOD_ID
    ) a
) b
GROUP BY b.Order
ORDER BY b.Order ASC

1 个答案:

答案 0 :(得分:1)

您需要一个LEFT JOIN,但是您也可以使用APPLY简化查询:

SELECT ranges.range, SUM(v.Remaining) as Suma,
       COUNT(*) as Docs
FROM (VALUES ('Late 1 to 14 days', 1),
             ('Late 15 to 30 day', 2),
             ('Late over 30 days', 3)
     ) ranges(range, ord) LEFT JOIN
     (dbo.MyData d CROSS APPLY
      (VALUES (DATEDIFF(day, d.PaymentDate, GETDATE()),
               WN - MA
              )
      ) v(DaysLate, Remaining) CROSS APPLY
      (VALUES (CASE WHEN v.DaysLate BETWEEN 1 AND 14
                    THEN 'Late 1 to 14 days'
                    WHEN v.DaysLate BETWEEN 15 AND 30
                    THEN 'Late 15 to 30 day'
                    ELSE 'Late over 30 days'
               END)
      ) v1(range)
     )
     ON v1.range = ranges.range                  
WHERE v.DaysLate > 0 AND
      KOD_ID = @KOD_ID
GROUP BY v.range, v.ord
ORDER BY v.ord;