我正在尝试使用ASP.NET为High Charts Bar图表放置一些数据。基本上,我有三个用户需要在他们登录系统时进行跟踪。要使用的变体是:
1)今天 2)本周 3)上周 4)上个月
所以,我已经为今天和上周创建了单独的tsql脚本,但是我现在对如何结合这两个状态最终有点困惑,最终会有四个。
SELECT Count(*) as CountToday from hitsTable WHERE Convert(date,hitDate) =
Convert(date,GETDATE()) Group by UserId
SELECT count(*) as CountLatWeek from hitTable
where hitDate between (DATEADD(week, DATEDIFF (week,0,GETDATE()),-1))
AND getDate() Group by UserId
google上的搜索引导我使用嵌套的select语句,这些语句似乎都与这两个语句形成了依赖关系。但是,我需要做的是生成一个结果表,如下所示:
修改
我已经设置了一个SQL小提琴,所以我们可以测试一些例子
http://www.sqlfiddle.com/#!6/a21ec
小提琴今天有tsql,上周有tsql(可能需要一些调整)
答案 0 :(得分:1)
Select Distinct
UserId
, ( Select Count(*) as CountToday from hitsTable h2
Where h2.UserId = h1.UserId
And Convert(date,hitDate) = Convert(date,GETDATE())
) As CountToday
, ( Select count(*) as CountLatWeek from hitsTable h2
Where h2.UserId = h1.UserId
And hitDate Between DATEADD(dd, -(DATEPART(dw, GetDate())-1)-7, GetDate())
And DATEADD(dd, 7-(DATEPART(dw, GetDate()))-7, GetDate())
) As CountLastWeek
FROM hitsTable h1
答案 1 :(得分:0)
尝试此查询
select
id,
sum(case when Convert(date,hitDate) = Convert(date,GETDATE()) then 1 else 0 end) as as CountToday,
sum(hitDate between (DATEADD(week, DATEDIFF (week,0,GETDATE()),-1)) AND getDate() then 1 else 0 end) as CountLatWeek,
...... -- Add more condition
from
hitsTable
group by
UserId
修改
select
userid,
sum(case when Convert(date,hitDate) =
Convert(date,GETDATE()) then 1 else 0 end) as cnt
from
hitstable
group by userid
| USERID | CNT |
|--------|-----|
| User1 | 3 |
| User2 | 0 |
答案 2 :(得分:0)
这是另一个基于@Avinash评论的替代方案。
Select
UserId
, CountTodayTable.CountToday
, CountLatWeekTable.CountLatWeek
, ...
FROM hitsTable h1
Inner Join
( Select Count(*) as CountToday from hitsTable h2
Where h2.UserId = h1.UserId
And Convert(date,hitDate) = Convert(date,GETDATE())
) CountTodayTable
On CountTodayTable.UserId = h1.UserId
Inner Join
( Select count(*) as CountLatWeek from hitTable h2
Where h2.UserId = h1.UserId
And hitDate between (DATEADD(week, DATEDIFF (week,0,GETDATE()),-1)) And getDate()
) CountLatWeekTable
On CountLatWeekTable.UserId = h1.UserId
...