![](/img/trans.png)
[英]How can i get current day, current week, current month, current year sales sum in single mysql query?
[英]Can I get the sum of the day, the week and the month in 1 MS SQL query?
當我有帶有列的表時
我可以在1個MS SQL查詢中為一天,一周和一個月的每個用戶獲得所有積分嗎? 這樣結果看起來像這樣:
|user |pointsDay|pointsWeek|pointsMonth|
|user1| 12 | 50 | 200 |
|user2| 10 | 60 | 222 |
...
這對您有幫助
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]
這應該工作:
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]
只需使用子查詢即可獲取所需的每個計算。
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.