SQL:选择不同年份之间的周数

时间:2016-01-17 18:43:32

标签: mysql sql

我想从数据库中分组并显示每周注册用户的数量。

我的代码几乎是完美的,但它在2016年不正常,这是数据库:

(1, '2013-10-14 16:22:10'),
(2, '2013-12-28 16:22:10'), 
(3, '2014-01-03 16:22:10'), 
(4, '2014-01-08 16:22:10'), 
(5, '2014-06-22 16:22:10'), 
(6, '2014-12-19 16:22:10'), 
(7, '2014-12-27 16:22:10'), 
(8, '2015-01-01 16:22:10'),
(9, '2015-01-07 16:22:10'),
(10, '2015-12-12 16:22:10'),
(11, '2015-12-28 16:22:10'),
(12, '2015-12-29 16:22:10'),
(13, '2016-01-05 16:22:10'),
(14, '2016-01-10 16:22:10'),
(15, '2016-01-15 16:22:10');

这是查询:

select  
  str_to_date(concat(yearweek(reg_data), ' monday'), '%X%V %W') as startingweek,
  YEAR(reg_data)*52+WEEK(reg_data, 1) - YEAR('2013-10-14')*52 - WEEK('2013-10-14', 1) + 1 as week_number,
  count(a.reg_data) as nr 
from users as a 
group by yearweek(reg_data, 1)
order by yearweek(reg_data, 1);

这是结果,2016年的最后两行不正确,我在括号中加入了我期望的正确值:

        startingweek        week_number    nr
October, 14 2013 00:00:00      1           1
December, 23 2013 00:00:00    11           1
December, 30 2013 00:00:00    12           1
January, 06 2014 00:00:00     13           1
June, 23 2014 00:00:00        36           1
December, 15 2014 00:00:00    62           1
December, 22 2014 00:00:00    63           1
December, 29 2014 00:00:00    64           1
January, 05 2015 00:00:00     65           1
December, 07 2015 00:00:00    113          1
December, 28 2015 00:00:00    116          2 
January, 04 2016 00:00:00     116 (117)    2
January, 11 2016 00:00:00     117 (118)    1

我知道问题与我在查询中使用的周数有关 - > 52,因为有些年份有53周,但我不知道如何根据年份动态改变。

我也在这里制作了一个方形小说:http://sqlfiddle.com/#!9/1e5df5/2

2 个答案:

答案 0 :(得分:0)

只需将计算更改为日期和开始日期之间的天数,然后除以7:

select  str_to_date(concat(yearweek(reg_data), ' monday'), '%X%V %W') as startingweek, 

   floor(datediff(min(reg_data),'2013-10-14')/7)+1 as week_number,

   count(a.reg_data) as nr
            from users as a 
            group by yearweek(reg_data, 1)
            order by yearweek(reg_data, 1);

请参阅fiddle

答案 1 :(得分:0)

许多数据库实现datediff()功能。所以DATEDIFF(week, date1, date2)就是你所需要的。不同的数据库可能会使用稍微不同的语法...