几周的mysql组

时间:2014-01-13 08:10:13

标签: php mysql

查询:

select  repdate, week(repdate,1) from calldrivers 
where repdate between '2013-10-01' and '2014-01-12' group by repdate

结果:

.
.
.
    2013-12-28 52 

    2013-12-29 52 

    2013-12-30 53 

    2013-12-31 53 

    2014-01-01 1 

    2014-01-02 1 

    2014-01-03 1 

    2014-01-04 1 

    2014-01-05 1 

    2014-01-06 2 

    2014-01-07 2 
.
.
.

正如您所看到的,今年的最后一周尚未正确分组。出于自动化目的,我需要将其自动化,以便mysql可以将2013年12月30日至 1月5日的一周识别为一周。

有没有解决方案来解决这个问题?

编辑**

我担心的是,当你逐周使用分组(repdate,1)时,它将分组作为一周的12月30日和31日以及从1月1日到5日作为另一周。但是他们应该是一个星期。

1 个答案:

答案 0 :(得分:1)

还有另一个可以帮助你的答案:

How to group by week in MySQL?

您可以用这种方式编写SQL查询

select  repdate, week(repdate,1) from calldrivers 
where repdate between '2013-10-01' and '2014-01-12' 
group by week(repdate,1)

这应该有效

编辑:测试用例

运行此测试用例,您应该在哪个模式下运行周功能 第一行表示测试用例日期的实际值。 在有几个查询和评论之后。评论是查询的结果

-- SUNDAY, MONDAY, THURSDAY, WEDNESDAY, SUNDAY, MONDAY
SELECT WEEK('2013-12-29', 0), WEEK('2013-12-30', 0), WEEK('2013-12-31', 0), WEEK('2014-01-01', 0), WEEK('2014-01-05', 0), WEEK('2014-01-06', 0);
-- 52, 52, 52, 0, 1, 1
SELECT WEEK('2013-12-29', 1), WEEK('2013-12-30', 1), WEEK('2013-12-31', 1), WEEK('2014-01-01', 1), WEEK('2014-01-05', 1), WEEK('2014-01-06', 1);
-- 52, 53, 53, 1, 1, 2
SELECT WEEK('2013-12-29', 2), WEEK('2013-12-30', 2), WEEK('2013-12-31', 2), WEEK('2014-01-01', 2), WEEK('2014-01-05', 2), WEEK('2014-01-06', 2);
-- 52, 52, 52, 52, 1, 1
SELECT WEEK('2013-12-29', 3), WEEK('2013-12-30', 3), WEEK('2013-12-31', 3), WEEK('2014-01-01', 3), WEEK('2014-01-05', 3), WEEK('2014-01-06', 3);
-- 52, 1, 1, 1, 1, 2
SELECT WEEK('2013-12-29', 4), WEEK('2013-12-30', 4), WEEK('2013-12-31', 4), WEEK('2014-01-01', 4), WEEK('2014-01-05', 4), WEEK('2014-01-06', 4);
-- 53, 53, 53, 1, 2, 2
SELECT WEEK('2013-12-29', 5), WEEK('2013-12-30', 5), WEEK('2013-12-31', 5), WEEK('2014-01-01', 5), WEEK('2014-01-05', 5), WEEK('2014-01-06', 5);
-- 51, 52, 52, 0, 0, 1
SELECT WEEK('2013-12-29', 6), WEEK('2013-12-30', 6), WEEK('2013-12-31', 6), WEEK('2014-01-01', 6), WEEK('2014-01-05', 6), WEEK('2014-01-06', 6);
-- 1, 1, 1, 1, 2, 2
SELECT WEEK('2013-12-29', 7), WEEK('2013-12-30', 7), WEEK('2013-12-31', 7), WEEK('2014-01-01', 7), WEEK('2014-01-05', 7), WEEK('2014-01-06', 7);
-- 51, 52, 52, 52, 52, 1

我认为周一到周日的模式是3,因为它在一年的第一周带来了12月30日和31日。如果您希望在一周内分组12月30日和31日以及在另一周内从12月1日到5月分组,则必须选择模式5.