2014-10-20 81 views
0

我试图创建一个报表查询,显示给定日期范围,所有名称,日期以及是否有数据。我非常接近,但是我对如何在数据中获得这些最终的零值感到茫然。因此,这里就是我想:SQL Server:两个表连接显示每天没有数据的所有行

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子句中是非常有意义的,它不为空或匹配日期。但是,如果我拿出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 

我这么近,我知道那里只是只是一些简单的我失踪,但每次尝试我作出修复它实际上会使结果变得更糟,所以我在这里寻求帮助。我想我只需要在外连接中修复查询以某种方式显示每个日期,如果我可以引用日期,则应用会更容易或更改其中的位置。但我一直无法弄清楚如何。

回答

1

添加ISNULL条件的SELECT子句中

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 
+0

原来如此!非常感谢。 – 2014-10-20 21:05:07