我正在尝试使用空数据填写日期,以便我的查询返回包含每个日期,并且不会跳过任何日期。
我的应用程序需要在报告中按日期计算活动预订,我不能跳过我的SQL返回的日期
我正在尝试使用日期表(我有一个表格,每个日期从1/1/2000到12/31/2030)通过在此日期表上执行RIGHT OUTER JOIN来实现此目的,这在交易时有效有一套活动。但是我有多套活动,每个活动都需要他们自己的全部日期,无论那个日期是否有预订。
我还有一个函数(DateRange),我发现允许这个:
SELECT IndividualDate FROM DateRange('d','11 / 01/2017','11 / 10/2018')
让我举一个例子,说明我得到的以及我想要得到的东西:
BAD: Without empty date rows:
date | activity_id | bookings
-----------------------------
1/2 | 1 | 5
1/4 | 1 | 4
1/3 | 2 | 6
1/4 | 2 | 2
GOOD: With empty date rows:
date | activity_id | bookings
-----------------------------
1/2 | 1 | 5
1/3 | 1 | NULL
1/4 | 1 | 4
1/2 | 2 | NULL
1/3 | 2 | 6
1/4 | 2 | 2
我希望这是有道理的。我完全可以加入一个只包含日期列表的表或使用DateRange表函数。但是没有给我上面的“好”结果。
答案 0 :(得分:1)
使用cross join
生成行,然后使用left join
填写值:
select d.date, a.activity_id, t.bookings
from DateRange('d', ''2017-11-01',''2018-11-10') d cross join
(select distinct activity_id from t) a left join
t
on t.date = d.date and t.activity_id = a.activity_id;
要了解您的数据以及来自该功能的内容有点困难。但无论数据来自哪里,这个想法都是一样的。
答案 1 :(得分:0)
我明白了:
SELECT TOP 100 PERCENT masterlist.dt, masterlist.activity_id, count(r_activity_sales_bymonth.bookings) AS totalbookings
FROM (SELECT c.activity_id, dateadd(d, b.incr, '2016-12-31') AS dt
FROM (SELECT TOP 365 incr = row_number() OVER (ORDER BY object_id, column_id), *
FROM (SELECT a.object_id, a.column_id
FROM sys.all_columns a CROSS JOIN
sys.all_columns b) AS a) AS b CROSS JOIN
(SELECT DISTINCT activity_id
FROM r_activity_sales_bymonth) AS c) AS masterlist LEFT OUTER JOIN
r_activity_sales_bymonth ON masterlist.dt = r_activity_sales_bymonth.purchase_date AND masterlist.activity_id = r_activity_sales_bymonth.activity_id
GROUP BY masterlist.dt, masterlist.activity_id
ORDER BY masterlist.dt, masterlist.activity_id