0

我目前的查询:

    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

这可以通过单个查询来实现吗?我知道如何在本周限制它,但不知道如何在前几周添加。

仅供参考,星期天午夜结束。提前致谢

4

1 回答 1

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)
于 2012-11-14T16:55:36.320 回答