SQL使用计算列添加行来创建视图

时间:2018-05-24 09:49:21

标签: mysql sql calculated-columns sql-view

我在MySQL中有一个表,它记录了特定进程的开始时间和结束时间。 它看起来像这样:

process_id process_start       process_end         data_1   data_2
         1 2017-12-05 15:21:55 2017-12-05 15:39:48 SD12891  8952020517397180000
         2 2017-12-05 15:40:19 2017-12-05 21:56:10 40001067 8952020017390610000
         3 2017-12-05 21:58:10 2017-12-05 22:04:46 SD12667  89014103279450400000
         4 2017-12-05 22:05:50 2017-12-05 22:08:11 40001067 89014103279450400000

我想创建一个这个数据库的视图,其中有一个名为" process_time"的新列。这将记录进程的小时[LEFT(process_start,13)],但是它将为进程启动的每小时创建一行(意味着它将在process_start和process_end之间的每小时创建一个新行)和每个小时新行,其他列中的所有值应保持不变。 所以上一张图片中的数据库看起来像这样:

process_id process_time  data_1   data_2
         1 2017-12-05 15 SD12891  8952020517397180000
         2 2017-12-05 15 40001067 8952020017390610000
         2 2017-12-05 16 40001067 8952020017390610000
         2 2017-12-05 17 40001067 8952020017390610000
         2 2017-12-05 18 40001067 8952020017390610000
         2 2017-12-05 19 40001067 8952020017390610000
         2 2017-12-05 20 40001067 8952020017390610000
         2 2017-12-05 21 40001067 8952020017390610000
         3 2017-12-05 21 SD12667  89014103279450400000
         3 2017-12-05 22 SD12667  89014103279450400000
         4 2017-12-05 22 40001067 89014103279450400000

如何做这样的事情?

1 个答案:

答案 0 :(得分:1)

一旦你有numbers表,这很容易......

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=0101c14c048f313b69405a77ad62caee

SELECT
  rounded.process_id,
  rounded.process_start,
  rounded.process_end,
  TIMESTAMPADD(HOUR, numbers.id, rounded.process_start_hour)   AS process_hour,
  rounded.data_1,
  rounded.data_2
FROM
(
  SELECT
    *,
    DATE_FORMAT(process_start,'%Y-%m-%d %H:00:00')   process_start_hour,
    DATE_FORMAT(process_end  ,'%Y-%m-%d %H:00:00')   process_end_hour
  FROM
    document
)
  rounded
INNER JOIN
  numbers
    ON numbers.id <= EXTRACT(HOUR FROM TIMEDIFF(process_end_hour, process_start_hour))
ORDER BY
  rounded.process_id,
  numbers.id

我强烈建议您在任何情况下将数字表转换为可行的数字表。