Sql-Server

在表格中插入缺失的日期

  • January 17, 2019

我有一個表格,其中有一列IDDateFrequency出現在那個特定的dateID

ID    date          Frequency
1     2014-05-18      5
1     2014-05-19      4
1     2014-05-20      25
2     2014-05-20      7
3     2014-05-18      4
3     2014-05-20      1
4     2014-05-18      6

我希望為每個ID目前不存在的日期插入日期(假設日期範圍從2014-05-182014-05-20)並為這些添加一個值 0 Frequency

例如,您可以看到

ID1 對所有三個日期都有觀察;

ID2 缺失2014-05-182014-05-19;

ID3 缺失2014-05-19

ID4 缺失2014-05-192014-05-20.

因此,輸出應如下所示

ID    date          Frequency
1     2014-05-18      5
1     2014-05-19      4
1     2014-05-20      25
2     2014-05-18      0
2     2014-05-19      0
2     2014-05-20      7
3     2014-05-18      4
3     2014-05-19      0
3     2014-05-20      1
4     2014-05-18      6
4     2014-05-19      0
4     2014-05-20      0

我從這個問題嘗試了以下內容。但是,這只會添加Frequency不存在於整個表中而不是在一個ID級別上的 0 日期。

DECLARE @s DATE = '20140518', @e DATE = '20140520';

SELECT c.date, Frequency = COALESCE(a.Frequency,0)
FROM dbo.Calendar AS c
LEFT OUTER JOIN dbo.table AS a
ON c.date = s.[date]
WHERE c.d >= @s
AND c.d < DATEADD(DAY, 1, @e);

使用上面的基本範例查詢,此程式碼應該可以滿足您的需求。重要變化:

  • CROSS JOIN 到應該在報告中的 ID 列表
  • 使用日期和 ID 加入數據表
  • 從 CROSS JOIN 表中選擇 id

編碼:

DECLARE @s DATE = '20140518', @e DATE = '20140520';

SELECT 
   i.ID, 
   c.[date], 
   Frequency = COALESCE(a.Frequency,0)
FROM 
   dbo.Calendar AS c
CROSS JOIN (SELECT DISTINCT x.ID FROM dbo.table x WHERE x.date >= @s AND x.date < DATEADD(day, 1, @e)) AS i
LEFT OUTER JOIN 
   dbo.table AS a
ON 
   c.[date] = a.[date]
   AND a.ID = i.ID
WHERE 
   c.[date]>= @s
   AND c.[date] < DATEADD(DAY, 1, @e);

引用自:https://dba.stackexchange.com/questions/227305