在以下时间范围内对应用程序进行分组

时间:2013-05-24 13:43:11

标签: sql sql-server

UserName |  Time Frame    |      No of Applications
Daniel   |  Week to date  | 3
Daniel   |  Month to date | 10
Daniel   | Year to date   |400

请帮我搞定上述格式,下面是我的陈述和输出。

select j.UserName, i.App_Date as "Time Frame", count(*) as "Num. of Applications" 
from tblApplication as i, tblUsers as j 
where i.User_ID = j.User_ID
group by j.UserName, i.App_Date
union
select distinct a.UserName, b.App_Date, count(b.User_ID) 
from tblUsers as a left join tblApplication as b on a.User_ID = b.User_ID 
where b.User_ID is null
group by a.UserName, b.App_Date

输出:

UserName    Time Frame         Num. of Applications
----------- ------------------ --------------------
Daniel                           3
Daniel  12/31/2012 12:00:00 AM   1
Daniel  1/1/2013 12:00:00 AM     1
Daniel  2/17/2013 10:37:15 AM    1
Daniel  2/18/2013 10:37:15 AM    1
Daniel  2/19/2013 10:37:15 AM    1
Daniel  2/20/2013 10:37:15 AM    1
Daniel  2/21/2013 10:37:15 AM    1
Daniel  2/22/2013 10:37:15 AM    1

2 个答案:

答案 0 :(得分:1)

要查看不同日期范围的不同行的结果,请尝试:

select u.UserName, d.TimeFrame, count(a.User_ID) 
from 
(select dateadd(d, 1-datepart(dw,getdate()), dateadd(dd, datediff(dd,0, getDate()), 0)) StartDate, 
        'Week to date' TimeFrame union all
 select dateadd(d, 1-datepart(dd,getdate()), dateadd(dd, datediff(dd,0, getDate()), 0)), 
        'Month to date' union all
 select dateadd(d, 1-datepart(dy,getdate()), dateadd(dd, datediff(dd,0, getDate()), 0)), 
        'Year to date') d
cross join tblUsers as u 
left join tblApplication as a 
       on u.User_ID = a.User_ID and d.StartDate <= a.App_Date
group by u.UserName, d.TimeFrame
order by u.UserName, max(d.StartDate) desc

SQLFiddle here

答案 1 :(得分:0)

您的查询需要通过多种方式进行改进。了解如何使用正确的join语法。 join条件属于on子句,而不属于where子句。另外,对表使用合理的别名。 ij并不意味着什么。 au更有意义(表名缩写)。

以下内容为每个用户将此逻辑分为三列:

select u.UserName,
       sum(case when date(now() - dayofweek(now())) = date(app_date - dayofweek(app_date)) then 1 else 0 end) as WeekToDate,
       sum(case when MONTH(now()) = month(app_date) then 1 else 0 end) as MonthToDate,
       sum(case when year(now()) = year(app_date) then 1 else 0 end) as YearToDate
from tblApplication a join
     tblUsers u
     on a.User_Id = u.User_id
group by u.UserName;