我正在尝试创建一个报告查询,显示给定的日期范围,所有名称,日期以及是否有数据。我真的很接近,但我对如何在数据中获得这些最终零值感到茫然。所以这就是我想要的:
Name ID Mth Day Count
Auburn 7261 10 14 0
Auburn 7261 10 15 0
Auburn 7261 10 16 0
Auburn 7261 10 17 0
Auburn 7261 10 18 0
Concord 7262 10 14 2
Concord 7262 10 15 0
Concord 7262 10 15 0
Concord 7262 10 17 1
Katey 7263 10 14 0
Katey 7263 10 15 0
Katey 7263 10 16 0
Katey 7263 10 17 0
Katey 7263 10 18 0
相反,我得到了:
Name ID Mth Day Count
Auburn 7261 10 14 0
Auburn 7261 10 15 0
Auburn 7261 10 16 0
Auburn 7261 10 17 0
Auburn 7261 10 18 0
Concord 7262 10 14 2
Concord 7262 10 17 1
Katey 7263 10 14 0
Katey 7263 10 15 0
Katey 7263 10 16 0
Katey 7263 10 17 0
Katey 7263 10 18 0
这是我的疑问:
SELECT PUE.Name as [Name], pue.EventID,
MONTH(dates.Date) AS Month, DAY(dates.Date) AS Day,
puc.idcount AS PicturesTaken
from (
select name, eventid from Events where
TourID = 444 and EventID > 7256 and EventID < 7323
) PUE
outer apply (
SELECT
Date = DateAdd( Day, n1.number * 10 + n0.number, '2014-10-14' )
FROM
(SELECT 1 AS number UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 0) as n0
CROSS JOIN
(SELECT 1 AS number UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 0) as n1
WHERE DateAdd( Day, n1.number * 10 + n0.number, '2014-10-14' ) BETWEEN '2014-10-14' AND '2014-10-18'
) dates
left outer join (
select eventid, convert(date,picturetakendate) as picdate, count(consumerdataid) as idcount from ConsumerData
where EventID > 7256 and EventID < 7323
group by eventid, convert(date,picturetakendate)
) puc
on pue.EventID = puc.EventID
where puc.picdate = dates.Date or puc.idcount is NULL
order by pue.eventid, MONTH(dates.Date), DAY(dates.Date)
我明白为什么零没有显示名称,这是外连接表的结果:
7262 2014-10-14 2
7262 2014-10-17 1
7265 2014-10-14 2
7266 2014-10-14 2
因此,在where子句中,它不是null或匹配日期是有意义的。但是如果我拿出where子句,我会为每个日期的每个计数得到一行,即:。
Concord 7262 10 14 2
Concord 7262 10 14 1
Concord 7262 10 15 1
Concord 7262 10 15 2
Concord 7262 10 16 2
Concord 7262 10 16 1
Concord 7262 10 17 1
Concord 7262 10 17 2
Concord 7262 10 18 2
Concord 7262 10 18 1
我非常接近,我知道只有一些简单的东西,我错过了但我每次尝试修复它实际上都会让结果变得更糟,所以我来这里寻求帮助。我想我只需要修复外部联接中的查询以某种方式显示每个日期,如果我可以引用日期应用将更容易或更改在哪里。但我一直无法弄清楚如何。
答案 0 :(得分:1)
在SELECT子句中添加ISNULL条件
SELECT PUE.Name as [Name], pue.EventID,
MONTH(dates.Date) AS Month, DAY(dates.Date) AS Day,
ISNULL(puc.idcount,0) AS PicturesTaken
将where子句转换为ON
on pue.EventID = puc.EventID
AND puc.picdate = dates.Date
而不是
where puc.picdate = dates.Date or puc.idcount is NULL