2016-11-02 282 views
0

我現在有一個腳本返回3列:顯示的日期範圍內的所有日期

代碼,日期,CountRows(見下圖):

enter image description here

每個鍵都有一個開始和結束日期。無論countRows是否爲0,我都希望所有日期都能返回,因爲該日期沒有數據。即第10行和第11行缺少兩個日期。

編輯

,所以我做了左的連接,如:

SELECT c.calendarDate, x.* 
FROM Calendar c 
LEFT JOIN (
SELECT key, orderDate, keyStartDate, keyEndDate, count(*) FROM multiple tables 
GROUP BY ...) x ON c.date >= x.startDdate AND c.date < DATEADD(DD,1,x.endDate) 

輸出:

enter image description here

那是做什麼的。基本上,orderDate不會返回數據不存在的所有日期。因此,我需要左連接以確保日期在開始日期和結束日期之間,以及orderdate沒有找到數據的位置,然後日曆以count(*)返回0來給出日期。

+0

標籤您與您正在使用的數據庫的問題。 –

+0

啊,是的,只是做到了。 – Faiz

回答

1

創建日曆表並將其保留加入你的數據。在這個例子中,我創建了一個臨時日曆表,但出於性能原因和重用性,我建議創建一個永久日曆表。

declare @calendar table (someDate date); 
declare @x date = '11/1/2015'; 

while @x <= '12/1/2015' begin 
    insert into @calendar values (@x); 
    set @x = dateadd(d, 1, @x); 
end; 

--generate some sample data 
declare @facts table (someDate date); 
insert into @facts values ('11/1/2015'), ('11/1/2015'), ('11/10/2015'), ('11/20/2015'), ('11/21/2015'), ('11/5/2015'), ('11/9/2015'); 

select 
    cal.someDate, 
    CountRows = count(f.SomeDate) 
from 
    @calendar cal 
    left join @facts f on cal.someDate = f.someDate 
group by 
    cal.someDate 
order by 
    cal.someDate; 

回答這個問題有創建日曆表中的一些好的建議:

How to create a Calender table for 100 years in Sql

+0

謝謝。該鏈接是非常有用的 – Faiz

+0

嘿,所以我做了表,並試圖離開加入它看到上面的問題。我在末尾編輯了它 – Faiz

+0

如果您選擇語句,您將從x中選擇*,但日期將在c中。因此,請執行以下操作:select c.date,x。* –

相關問題