gpt4 book ai didi

sql - Oracle SQL 中的组合查询

转载 作者:行者123 更新时间:2023-12-01 12:36:30 25 4
gpt4 key购买 nike

我有表雇员:

|id|datetime           |in-out|
|1 |2015-03-03 06:00:00|in |
|1 |2015-03-03 14:15:00|out |
|1 |2015-03-04 06:00:00|in |
|1 |2015-03-04 15:00:00|out |

我想创建 View ,其中包含雇员 (id) 的工作时长信息,这样

|id|datetime_in        |datetime_out       |how_log|
|1 |2015-03-03 06:00:00|2015-03-03 14:00:00|08:15 |
|1 |2015-03-04 06:00:00|2015-03-03 15:00:00|09:00 |

你能帮帮我吗?

最佳答案

这是另一种获得结果的方法 - 使用 pivot 子句(Oracle 11g 及更高版本):

select id
, to_char(in1, 'yyyy-mm-dd hh24:mi:ss') as datetime_in
, to_char(out1, 'yyyy-mm-dd hh24:mi:ss') as datetime_out
, to_char(extract(hour from numtodsinterval(out1-in1, 'day'))
, 'fm00') || ':' ||
to_char(extract(minute from numtodsinterval(out1-in1, 'day'))
, 'fm00') as how_long
from ( select id
, datetime
, in_out
, row_number() over(partition by id, in_out
order by datetime) as rn
from tb1
order by datetime
)
pivot (
max(datetime) for in_out in ('in' as in1, 'out' as out1)
)
order by id, datetime_in

结果:

        ID DATETIME_IN         DATETIME_OUT        HOW_LONG
---------- ------------------- ------------------- --------
1 2015-03-03 06:00:00 2015-03-03 14:15:00 08:15
1 2015-03-04 06:00:00 2015-03-04 15:00:00 09:00

SQLFiddle Demo

关于sql - Oracle SQL 中的组合查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29209228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com