1

我们需要在周五至周五的基础上运行全年的报告。我没有看到week()为此方便的功能。

假设我们有一个表Summary,有两列 -countcreation_date。我需要根据creation_date从周五到周五的时间汇总计数。这需要运行几年。

任何建议,将不胜感激。

4

3 回答 3

1

这是一个查询告诉你从今天开始的上一个星期五和下一个星期四

SELECT DATE(week_beg),DATE(week_end) FROM
(SELECT daywk_beg + INTERVAL 0 second week_beg,
daywk_beg + INTERVAL 604799 second week_end
FROM (SELECT (DATE(NOW()) - INTERVAL daysbacktoday DAY) daywk_beg
FROM (SELECT SUBSTR('2345601',wkndx,1) daysbacktoday
FROM (SELECT DAYOFWEEK(dt) wkndx FROM (SELECT DATE(NOW()) dt)
AAAAA) AAAA) AAA) AA) A;

这是今天的结果

mysql> SELECT DATE(week_beg),DATE(week_end) FROM
    -> (SELECT daywk_beg + INTERVAL 0 second week_beg,
    -> daywk_beg + INTERVAL 604799 second week_end
    -> FROM (SELECT (DATE(NOW()) - INTERVAL daysbacktoday DAY) daywk_beg
    -> FROM (SELECT SUBSTR('2345601',wkndx,1) daysbacktoday
    -> FROM (SELECT DAYOFWEEK(dt) wkndx FROM (SELECT DATE(NOW()) dt)
    -> AAAAA) AAAA) AAA) AA) A;
+----------------+----------------+
| DATE(week_beg) | DATE(week_end) |
+----------------+----------------+
| 2013-03-22     | 2013-03-28     |
+----------------+----------------+
1 row in set (0.00 sec)

我在 DBA StackExchange 中写了一个这样的查询

这是一个示例表

CREATE TABLE summary
(
    id int not null auto_increment,
    ...
    `count` int not null default 0,
    creation_date date,
    primary key (id)
);

要让您的查询根据星期五计算结果,您需要这个

SELECT SUM(`count`) count_sum,friday FROM
(SELECT `count`,DATE(week_beg) friday
(SELECT daywk_beg + INTERVAL 0 second week_beg,
daywk_beg + INTERVAL 604799 second week_end,`count`
FROM (SELECT `count`,(DATE(NOW()) - INTERVAL daysbacktoday DAY) daywk_beg
FROM (SELECT `count`,SUBSTR('2345601',wkndx,1) daysbacktoday
FROM (SELECT `count`,DAYOFWEEK(dt) wkndx FROM
(SELECT `count`,creation_date FROM dt)
AAAAA) AAAA) AAA) AA) A) fri
GROUP BY friday;

试试看 !!!

于 2013-03-26T19:14:04.487 回答
0
Select 
count, creation_date,
from
(
    SELECT 
    count, creation_date
    DATEDIFF(week, '2013-03-30', date) AS WeekNumber
    FROM Summary
)
GROUP BY
count,
creation_date,
WeekNumber

您将输入您的开始日期来代替2013-03-30

于 2013-03-26T17:24:31.667 回答
0

你可以分组

YEARWEEK(`date` - INTERVAL 5 DAY)

或者你可以用这个来计算你的start_week_dateend_week_date

SELECT
  `date`,
  `date` - INTERVAL (DAYOFWEEK(`date`) + 1) % 7 DAY start_week_date,
  `date` + INTERVAL 6 - (DAYOFWEEK(`date`) + 1) % 7 DAY end_week_date
FROM
  dates

请看这个小提琴

所以你的查询可能是这样的:

SELECT
  creation_date - INTERVAL (DAYOFWEEK(creation_date) + 1) % 7 DAY start_week_date,
  SUM(count)  --- or your aggregate function
FROM
  Summary
GROUP BY
  creation_date - INTERVAL (DAYOFWEEK(creation_date) + 1) % 7 DAY start_week_date
于 2013-03-26T18:34:01.493 回答