2011-07-24 45 views
1
declare @customerID int 
set @customerID=1 


;with cteDates as 
(
    select dateadd(hh, datediff(hh, 0, getdate()), 0) as [Date] 
    union all 
    select dateadd(hh, -1, [Date]) as [Date] 
    from cteDates 
    where [Date] > dateadd(hh, -23, getdate()) 
) 
select 
    sum(coalesce(field1,0)) field1, 
    sum(coalesce(field2,0)) field2, 
    sum(coalesce(field3,0)) field3, 
    sum(coalesce(field4,0)) field4, 
    sum(coalesce(field5,0)) field5, 
    d.[Date] 
from cteDates as d left join [Statistics] s 
on d.Date=s.date 
where [email protected] and s.date>dateadd(hh,-24,getdate()) 
group by d.Date 

我想要得到一定的客戶每小時的統計,如果沒有價值,我想選擇0反正...爲什麼這個tsql查詢沒有選擇它的意圖?

此查詢選擇,存在於統計表只行即使我已經留下了加盟軋光CTE ...

感謝,...

回答

1

這是因爲你的WHERE子句中指的統計數據表。

嘗試:

declare @customerID int 
set @customerID=1 

;with cteDates as 
(
select dateadd(hh, datediff(hh, 0, getdate()), 0) as [Date] 
union all 
select dateadd(hh, -1, [Date]) as [Date] 
from cteDates 
where [Date] > dateadd(hh, -23, getdate()) 
) 
select 
sum(coalesce(field1,0)) field1, 
sum(coalesce(field2,0)) field2, 
sum(coalesce(field3,0)) field3, 
sum(coalesce(field4,0)) field4, 
sum(coalesce(field5,0)) field5, 
d.[Date] 
from cteDates as d left join [Statistics] s 
on d.Date=s.date 
and [email protected] and s.date>dateadd(hh,-24,getdate()) 
group by d.Date 
+0

非常感謝你的l33t! – eugeneK

+0

no problemo .... –

+0

http://wiki.lessthandot.com/index.php/WHERE_conditions_on_a_LEFT_JOIN – HLGEM

相關問題