[英]Can I get the sum of the day, the week and the month in 1 MS SQL query?
When I have a table with the columns 当我有带有列的表时
Can I get all points for each user of the day, the week and the month in 1 MS SQL query? 我可以在1个MS SQL查询中为一天,一周和一个月的每个用户获得所有积分吗? So that the result looks something like this: 这样结果看起来像这样:
|user |pointsDay|pointsWeek|pointsMonth|
|user1| 12 | 50 | 200 |
|user2| 10 | 60 | 222 |
... ...
This help you, 这对您有帮助
SELECT [USER],
SUM(POINTS) POINTSMONTH,
SUM(CASE WHEN CREATEDATE>DATEADD(DAY,-7,GETDATE()) THEN POINTS ELSE 0 END) POINTSWEEK,
SUM(CASE WHEN CREATEDATE>DATEADD(DAY,-1,GETDATE()) THEN POINTS ELSE 0 END) POINTSDAY
FROM USERS
WHERE CREATEDATE> DATEADD(DAY,-30,GETDATE())
GROUP BY [USER]
This should work: 这应该工作:
WITH Src AS
(
SELECT * FROM (VALUES
('user1', 100, DATEADD(DAY,-50,GETDATE())),
('user1', 2, DATEADD(DAY,-15,GETDATE())),
('user1', 3, DATEADD(DAY,-5,GETDATE())),
('user1', 7, GETDATE()),
('user2', 4, GETDATE())
)T([User],Points,CreatedAt)
) --Test data
SELECT [User],
SUM(Points) Monthly,
SUM(CASE WHEN CreatedAt>DATEADD(DAY,-7,GETDATE()) THEN Points ELSE 0 END) Weekly,
SUM(CASE WHEN CreatedAt>DATEADD(DAY,-1,GETDATE()) THEN Points ELSE 0 END) Daily
FROM Src
WHERE CreatedAt > DATEADD(DAY,-30,GETDATE())
GROUP BY [User]
Just use subqueries to get every calculation that you need. 只需使用子查询即可获取所需的每个计算。
select user,
(select sum(points) from my_table as points where points.user = users.user and createdAt = getDate()) as pointsDay,
(select sum(points) from my_table as points where points.user = users.user and datepart(week, createdAt) = datepart(week, getDate()) and datepart(year, createdAt) = datepart(year, getDate())) as pointsWeek,
(select sum(points) from my_table as points where points.user = users.user and datepart(month, createdAt) = datepart(month, getDate()) and datepart(year, createdAt) = datepart(year, getDate())) as pointsMonth,
from my_table as users
group by user
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.