0
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
4

2 回答 2

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在这里

于 2013-05-24T14:05:07.190 回答
0

您的查询需要以多种方式改进。学习如何使用正确的join语法。join条件属于子句而on不是where子句。此外,为表使用合理的别名。 i并且j没有任何意义。 a并且u更有意义(表名的缩写)。

下面为每个用户将此逻辑分为三列:

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;
于 2013-05-24T13:52:55.527 回答