我当前的查询:
Select `userSubUnitsID`, `userSubUnits`.`userID`, CONCAT(`u`.`fname`,' ',`u`.`lname`) AS `full`, `pID`, SUM(`quantComp`) AS `total`
From `userSubUnits`
JOIN `u` ON `u`.`userID` = `userSubUnits`.`userID`
GROUP BY `userID`
我需要的是约会。所以看起来会更像这样。
+-----+------------+----------+-------------+
|user |current week|prev week |two weeks ago|
+-----+------------+----------+-------------+
|John | 564| 354| 687|
+-----+------------+----------+-------------+
|Paul | 451| 328| 845|
+-----+------------+----------+-------------+
etc
单个查询是否可以实现?我知道如何限制本周,但不知道如何在前几周添加。
仅供参考,周末在周日午夜结束。 提前致谢
答案 0 :(得分:2)
SELECT user, SUM(WEEKOFYEAR(datefield) = WEEKOFYEAR(now()) AS current_week,
SUM(WEEKOFYEAR(datefield) = WEEKOFYEAR(now() - INTERVAL 1 WEEK)) AS last_week,
SUM(WEEKOFYEAR(datefield) = WEEKOFYEAR(now() - INTERVAL 2 WEEK)) AS two_weeks_ago
FROM ...
GROUP BY WEEKOFYEAR(now())
丑陋,但应该做的伎俩。请注意,如果您的日期跨越一年边界,则此操作将失败。为了解决这个问题,你必须添加一些额外的基于年的逻辑。
同样,你最好还是做这种转型的客户端。扩展是丑陋的,如果你需要开始做超过几周的事情,很快就会变得非常低效,例如:
SELECT user, YEAR(datefield), WEEKOFYEAR(datefield), COUNT(*)
FROM ...
GROUP BY YEAR(datefield), WEEKOFYEAR(datefield)