从表中查找每周摘要

时间:2010-06-21 06:56:19

标签: sql data-analysis

我在这里编写一个SQL语句,用于从表中查找每周摘要。我有一个包含以下字段的表:

UIN, Date, Staff, work_hours

现在我想收集一周内工作人员工作多少小时的信息。

2 个答案:

答案 0 :(得分:4)

很难从您的问题中得知,但如果您要查找每位员工一周内的总小时数,请尝试以下方法:

SELECT Staff, SUM(work_hours)
FROM YourTable
WHERE Date BETWEEN week_start_day AND week_end_day
GROUP BY Staff

否则,如果您要查找按周汇总的完整报告,您可以尝试以下操作,这将为您提供按周汇总的每位员工的每周工作时间:

SELECT YEAR(Date), WEEK(Date), Staff, SUM(work_hours)
FROM YourTable
GROUP BY YEAR(Date), WEEK(Date), Staff
ORDER BY YEAR(Date), WEEK(Date)

答案 1 :(得分:3)

您可能想尝试以下内容:

SELECT    staff, 
          WEEK(date) week_no, 
          SUM(work_hours) as work_hours_sum
FROM      log
GROUP BY  staff, WEEK(date)
ORDER BY  WEEK(date), staff;

测试用例(MySQL):

CREATE TABLE log (
    uin int auto_increment primary key, 
    date date, 
    staff int, 
    work_hours int
);

INSERT INTO log (date, staff, work_hours) VALUES ('2010-06-01', 1, 5);
INSERT INTO log (date, staff, work_hours) VALUES ('2010-06-01', 2, 7);
INSERT INTO log (date, staff, work_hours) VALUES ('2010-06-02', 1, 2);
INSERT INTO log (date, staff, work_hours) VALUES ('2010-06-02', 2, 1);
INSERT INTO log (date, staff, work_hours) VALUES ('2010-06-08', 1, 2);
INSERT INTO log (date, staff, work_hours) VALUES ('2010-06-08', 2, 5);
INSERT INTO log (date, staff, work_hours) VALUES ('2010-06-09', 1, 6);
INSERT INTO log (date, staff, work_hours) VALUES ('2010-06-09', 2, 5);

结果:

+-------+---------+----------------+
| staff | week_no | work_hours_sum |
+-------+---------+----------------+
|     1 |      22 |              7 |
|     2 |      22 |              8 |
|     1 |      23 |              8 |
|     2 |      23 |             10 |
+-------+---------+----------------+
4 rows in set (0.00 sec)