由于报告的类型不同,我为这个项目创建了几个不同的select语句,但现在我有一个有趣的场景,但我认为它会更常见,或者我只是没有使用正确的术语
我最近的障碍是我试图将两张桌子加在一起,但不是在同一行,而是在同一列......
所以我有这个查询根据扫描时间分区挑选票号...
<div>IT WORKS</div>
这是它的输出 -
WITH ticket AS
(
SELECT ticket_trail.PickT_Num
,ticket_trail.ticket_status
,ticket_trail.ID
,cast(ticket_trail.Time_stamp as DateTime)as 'time_stamped',
ROW_NUMBER() OVER(PARTITION BY ticket_trail.PickT_Num ORDER BY
ticket_trail.time_stamp Asc) as RowNum
FROM
ticket_trail
)
SELECT
ticket.RowNum,ticket.PickT_Num AS 'Pick Ticket'
,ticket.ID AS id1
,ticket.ticket_status as Ticket_Status
,ticket.time_stamped as start_time
,Row2.ID id2,ISNULL(Row2.time_stamped,GetDate()) AS "End Time"
,DATEDIFF(MINUTE,ticket.time_stamped,ISNULL(Row2.time_stamped,GetDate()))
From
ticket left join ticket AS Row2
ON
ticket.RowNum +1 = Row2.RowNum AND ticket.PickT_Num = Row2.PickT_Num
确定以便Query完美运行!!然而,它并没有讲述整个故事!我需要能够添加另一个条目作为&#39; 0&#39; RowNum | Pick Ticket | id1 | Ticket_Status | start_time | id2 | End Time | Diff
1 | 4628750 | 65 | Yellow | 2017-11-08 09:24:14.000 | 66 | 2017-11-08 09:24:26.000 | 0
2 | 4628750 | 66 | Green | 2017-11-08 09:24:26.000 | NULL | 2017-11-21 16:33:12.733 | 19149
1 | 4647142 | 78 | Yellow | 2017-11-08 09:28:02.000 | 79 | 2017-11-08 09:28:08.000 | 0
2 | 4647142 | 79 | Flashing | 2017-11-08 09:28:08.000 | 295 | 2017-11-08 14:14:10.000 | 286
3 | 4647142 | 295 | Green | 2017-11-08 14:14:10.000 | NULL | 2017-11-21 16:33:12.733 | 18859
1 | 4647973 | 1 | Blue | 2017-11-08 09:02:04.000 | 21 | 2017-11-08 09:06:05.000 | 4
2 | 4647973 | 21 | Green | 2017-11-08 09:06:05.000 | NULL | 2017-11-21 16:33:12.733 | 19167
1 | 4648017 | 2 | Blue | 2017-11-08 09:02:26.000 | 22 | 2017-11-08 09:05:56.000 | 3
2 | 4648017 | 22 | Green | 2017-11-08 09:05:56.000 | NULL | 2017-11-21 16:33:12.733 | 19168
1 | 4648030 | 41 | Blue | 2017-11-08 09:18:20.000 | 54 | 2017-11-08 09:22:39.000 | 4
2 | 4648030 | 54 | Green | 2017-11-08 09:22:39.000 | NULL | 2017-11-21 16:33:12.733 | 19151
来自另一个名为RowNum
的表中的每个PickT_Num
,该表提供了一个名为Orders_ent
的time_stamp
所以我认为它必须是一个Case声明,但我不知道从哪里开始...
输出中可以有Printed
,但基本上我正在寻找的是:
NULLS
RowNum | Pick Ticket | id1 | Ticket_Status | start_time | id2 | End Time | Diff
0 | 4628750 | NULL | Printed | 2017-11-08 09:20:14.000 | 65 | 2017-11-08 09:24:14.000 | 4
1 | 4628750 | 65 | Yellow | 2017-11-08 09:24:14.000 | 66 | 2017-11-08 09:24:26.000 | 0
2 | 4628750 | 66 | Green | 2017-11-08 09:24:26.000 | NULL | 2017-11-21 16:33:12.733 | 19149
表看起来像这样......
Orders_ent
答案 0 :(得分:0)
尝试添加UNION ALL
和ORDER BY
... -- your query is here
UNION ALL
SELECT
0 RowNum,
e.PickT_Num,
NULL id1,
'Printed' Ticket_Status,
e.Date_Created,
t.ID id2,
e.Pick_Ticket_Printed_DATE_Time,
DATEDIFF(MINUTE,e.Date_Created,ISNULL(e.Pick_Ticket_Printed_DATE_Time,GetDate()))
FROM Orders_ent e
JOIN
(
SELECT PickT_Num,ID
FROM ticket
WHERE RowNum=1
) t
ON e.PickT_Num=t.PickT_Num
ORDER BY 'Pick Ticket',RowNum