sql统计之谜

时间:2011-03-15 09:35:56

标签: sql-server-2005 tsql

我正在使用SQL Server 2005并尝试以某种格式获取某些统计数据,因为它被加载到不应更改的图形中。

图表接受日期,类型和总和。在我的案例中输入域名,总和是这个网站每天的销售量。

现在我有两个数据库表,UsersSalesUsersuserIDregistrationSite列。 Sales获得saleIDuserIDsum。这是一个查询,我得到了我的统计数据的所有细节,但有一个问题。

即使在此日期没有此域名的销售以使图表生效,我也应该在“选择”中获得“0”值。有办法吗?

select 
    sum(s.sum) sum,u.registrationSite,
    dateadd(dd, datediff(dd, 0, s.date), 0) date 
from Users u
right join Sales s on u.userid=s.userid
where 
    s.date > dateadd(mm, -1, getdate())
group by 
    registrationSite,dateadd(dd,datediff(dd,0,s.date),0)
order by 
    dateadd(dd, datediff(dd, 0, s.date), 0)

1 个答案:

答案 0 :(得分:1)

也许这是你正在寻找的输出,或者你可以修改你得到你想要的。

cteDates会建立一个从今天和一个月前的日期列表。针对distinct RegistrationSite的交叉联接可确保为每个日期和网站组合获得一行。销售额left outer join获取每个日期/网站行的总和。

;with cteDates as
(
  select dateadd(dd, datediff(dd, 0, getdate()), 0) as [Date]
  union all
  select dateadd(dd, -1, [Date]) as [Date]
  from cteDates
  where [Date] > dateadd(mm, -1, getdate())
)
select
  sum(coalesce(s.[Sum], 0)) as [Sum],
  r.RegistrationSite,
  cd.[Date]
from cteDates as cd
  cross join (select distinct RegistrationSite
              from Users) as r
  left outer join 
      (select [Date], [sum], RegistrationSite
       from Sales
         inner join Users
           on Sales.UserID = Users.UserID) as s
   on cd.[Date] = dateadd(dd, datediff(dd, 0, s.[Date]), 0) and
      r.RegistrationSite = s.RegistrationSite
group by r.RegistrationSite, cd.[Date]
order by cd.[Date]

结果

0           site 1           2011-03-12 00:00:00.000
0           site 2           2011-03-12 00:00:00.000
0           site 1           2011-03-13 00:00:00.000
0           site 2           2011-03-13 00:00:00.000
60          site 1           2011-03-14 00:00:00.000
50          site 2           2011-03-14 00:00:00.000
0           site 1           2011-03-15 00:00:00.000
40          site 2           2011-03-15 00:00:00.000