Add a row for TOTAL in a sql query result

夙愿已清 提交于 2019-12-11 11:07:00

问题


I have a SQL table as

empid  to_day     clock_in clock_out late_reason
001Acc 01/04/2016  9:12:08 18:33:57  Office work
001Acc 02/04/2016 10:12:08 19:33:57  Home work
001Acc 03/04/2016 11:12:08 20:33:57  Sick
001Acc 04/04/2016 10:12:08 19:53:57  Car disorder
001Acc 05/04/2016 13:12:08 19:33:57  Hospital

After ran following query:

SELECT
    to_day,
    (
        TIME_TO_SEC(clock_out) - TIME_TO_SEC(clock_in)
    ) AS worktime,
    late_reason
FROM
    myTable
WHERE
    emp_id = '001Acc'
AND (
    to_day BETWEEN "2016-04-01"
    AND "2016-04-05"
)

I can get

to_day     worktime late_reason
01/04/2016    33709 Office work
02/04/2016    33709 Home work
03/04/2016    33709 Sick
04/04/2016    34909 Car disorder
05/04/2016    22909 Hospital
***Total        158945***

(without the TOTAL row). But I want to add a row for total of worktime column from the query (in red in the image). Is it possible?

Please help me to rewrite the query.

Thanks.


回答1:


Personally, I think such problems are best left to application level code, but just for fun...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(empid INT NOT NULL
,clock_in DATETIME NOT NULL
,clock_out DATETIME NULL
,late_reason VARCHAR(20) NULL
,PRIMARY KEY(empid,clock_in)
);

INSERT INTO my_table VALUES
(1 ,'2016/04/01  9:12:08','2016/04/01 18:33:57','Office work'),
(1 ,'2016/04/02 10:12:08','2016/04/02 19:33:57','Home work'),
(1 ,'2016/04/03 11:12:08','2016/04/03 20:33:57','Sick'),
(1 ,'2016/04/04 10:12:08','2016/04/04 19:53:57','Car disorder'),
(1 ,'2016/04/05 13:12:08','2016/04/05 19:33:57','Hospital');

SELECT COALESCE(date,'Total') date
     , diff 
  FROM 
     ( SELECT DATE(clock_in) date
            , SUM(TIME_TO_SEC(TIMEDIFF(clock_out,clock_in))) diff 
         FROM my_table 
        GROUP 
           BY date WITH ROLLUP
     ) x;
+------------+--------+
| date       | diff   |
+------------+--------+
| 2016-04-01 |  33709 |
| 2016-04-02 |  33709 |
| 2016-04-03 |  33709 |
| 2016-04-04 |  34909 |
| 2016-04-05 |  22909 |
| Total      | 158945 |
+------------+--------+


来源:https://stackoverflow.com/questions/37211482/add-a-row-for-total-in-a-sql-query-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!