我正在尝试编写一个查询,该查询返回订单从开始到完成所用的时间。
我的表格如下所示。
Order No. Action DateTime
111 Start 3/23/2018 8:18
111 Complete 3/23/2018 9:18
112 Start 3/24/2018 6:00
112 Complete 3/24/2018 11:10
现在我正在尝试计算多个订单的开始和完成之间的日期差异,以下是我的查询:
Declare @StartDate VARCHAR(100), @EndDate VARCHAR(100), @Operation VARCHAR(100)
declare @ORDERTable table
(
order varchar(1000)
)
insert into @ORDERTable values ('111')
insert into @ORDERTable values ('112')
Select @Operation='Boiling'
set @EndDate = (SELECT DATE_TIME from PROCESS WHERE ACTION='COMPLETE' AND ORDER in (select order from @ORDERTable) AND OPERATION=@Operation)
---SELECT @EndDate
set @StartDate = (SELECT DATE_TIME from PROCESS WHERE ACTION='START' AND ORDER in (select order from @ORDERTable) AND OPERATION=@Operation)
---SELECT @StartDate
SELECT DATEDIFF(minute, @StartDate, @EndDate) AS Transaction_Time
所以,我可以输入多个订单,但我也希望获得多个输出。
我的第二个问题是,如果我能够获得多个记录作为输出,我将如何确定哪个约会是哪个订单?
等待你的回答。提前谢谢。
我正在使用MSSQL。
答案 0 :(得分:1)
您可以将表格拆分为两个临时表,cte,等等,然后将它们连接在一起以查找完成所需的时间
DECLARE @table1 TABLE (OrderNO INT, Action VARCHAR(100), datetime datetime)
INSERT INTO @table1 (OrderNO, Action, datetime)
VALUES
(111 ,'Start' ,'3/23/2018 8:18'),
(111 ,'Complete' ,'3/23/2018 9:18'),
(112 ,'Start' ,'3/24/2018 6:00'),
(112 ,'Complete' ,'3/24/2018 11:10')
;with cte_start AS (
SELECT orderno, Action, datetime
FROM @table1
WHERE Action = 'Start')
, cte_complete AS (
SELECT orderno, Action, datetime
FROM @table1
WHERE Action = 'Complete')
SELECT
start.OrderNO, DATEDIFF(minute, start.datetime, complete.datetime) AS duration
FROM cte_start start
INNER JOIN cte_complete complete
ON start.OrderNO = complete.OrderNO
答案 1 :(得分:1)
您可以按订单号进行汇总,并使用MAX
或MIN
与CASE WHEN
进行汇总,以获取开始或结束时间:
select
order_no,
max(case when action = 'Start' then date_time end) as start_time,
max(case when action = 'Completed' then date_time end) as end_time,
datediff(
minute,
max(case when action = 'Start' then date_time end),
max(case when action = 'Completed' then date_time end)
) as transaction_time
from process
group by order_no
order by order_no;
答案 2 :(得分:0)
为什么不尝试使用基于集合的解决方案来解决此问题?毕竟,这就是RDBMS的用途。假设您在表格变量({1}}中拥有您感兴趣的订单,它将符合以下内容:
@ORDERTable(Order)
如果SELECT DISTINCT
[Order No.]
, DATEDIFF(
minute,
FIRST_VALUE([DateTime]) OVER (PARTITION BY [Order No.] ORDER BY [DateTime] ASC),
FIRST_VALUE([DateTime]) OVER (PARTITION BY [Order No.] ORDER BY [DateTime] DESC)
) AS Transaction_Time
FROM tableName
WHERE [Order No.] IN (SELECT Order FROM @ORDERTable);
属性中的所有值都是开始或完成,但是如果它们之间还有其他值,则此查询有效。
详细了解Action
窗口函数check out the documentation。
注意:适用于SQL Server 2012或更高版本。