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
我這麼近,我知道那裏只是只是一些簡單的我失蹤,但每次嘗試我作出修復它實際上會使結果變得更糟,所以我在這裏尋求幫助。我想我只需要在外連接中修復查詢以某種方式顯示每個日期,如果我可以引用日期,則應用會更容易或更改其中的位置。但我一直無法弄清楚如何。
原來如此!非常感謝。 – 2014-10-20 21:05:07