为什么这个tsql查询没有选择它的意图?

时间:2011-07-24 14:03:36

标签: sql sql-server-2005 tsql

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 s.customerID=@customerID and s.date>dateadd(hh,-24,getdate())
group by d.Date

我想获得某个客户的每小时统计数据,如果没有价值我想要选择0 ...

此查询仅选择Statistics表中存在的行,即使我已使用calender CTE保持联接...

谢谢,......

1 个答案:

答案 0 :(得分: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 s.customerID=@customerID and s.date>dateadd(hh,-24,getdate())
group by d.Date