简体   繁体   English

MySQL有几个日期范围

[英]MySQL with several date ranges

My current query: 我目前的查询:

    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`

What I need is to get this by a date. 我需要的是通过约会得到这个。 So it will look more like this. 所以看起来会更像这样。

    +-----+------------+----------+-------------+
    |user |current week|prev week |two weeks ago|
    +-----+------------+----------+-------------+
    |John |         564|       354|          687|
    +-----+------------+----------+-------------+
    |Paul |         451|       328|          845|
    +-----+------------+----------+-------------+
    etc

Is this possible with a single query? 单个查询可以实现吗? I know how to limit it for the current week but not how to add in the previous weeks. 我知道如何限制本周,但不知道如何在前几周添加。

FYI, Weeks end Sunday at midnight. 仅供参考,星期日午夜结束。 Thanks in advance 提前致谢

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())

ugly, but should do the trick. 丑陋,但应该做的伎俩。 Note that this will fail if your dates span a year boundary. 请注意,如果您的日期跨越一年边界,则此操作将失败。 To get around that, you'd have to add in some extra year-based logic. 要解决这个问题,你必须添加一些额外的基于年的逻辑。

As well, you'd be better off doing this kind of transformation client-side. 同样,你最好还是做这种转型的客户端。 It's ugly to expand, and will very quickly get hideously inefficient if you need to start doing more than just a few weeks, eg: 扩展是丑陋的,如果你需要开始做的不仅仅是几周,那么很快就会变得非常低效,例如:

SELECT user, YEAR(datefield), WEEKOFYEAR(datefield), COUNT(*)
FROM ...
GROUP BY YEAR(datefield), WEEKOFYEAR(datefield)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM