SQL将单独的时间戳合并到每个序列号成1行

时间:2019-01-30 15:29:30

标签: sql sql-server tsql timestamp pivot

我的tableA的列为SerialNumber(integer),LineNumber(integer),SectionNumber(integer)和TimeComplete(Datetime)。该表跟踪在任何给定生产线上的任何给定工位何时完成序列号为x的产品。我现在正在尝试建立一个查询,该查询将显示何时为任何给定的序列号完成任何给定的工作站,但是问题是我在每节完成时收到一个订单项。我希望输出为带有序列号的一行,然后为每个部分加上时间戳。

Current output
SerialNumber   Station1    Station2   Station3   Station4
123            TimeStamp   null       null       null
123            null        timestamp  null       null
123            null        null       timestamp  null
123            null        null       null       timestamp

Desired output
SerialNumber  Station1    Station2   Station3   Station4
123           TimeStamp   Timestamp  Timestamp  Timestamp

当前sql查询

SELECT
distinct
tableA.Serial,
case when tableA.Section = 4 then tableA.TimeComplete
end as 'Station1',
case when tableA.Section = 5 then tableA.TimeComplete
end as 'Station2',
case when tableA.Section = 2 then tableA.TimeComplete
end as 'Station3',
case when tableA.Section = 6 then tableA.TimeComplete
end as 'Station4',
FROM tableA

1 个答案:

答案 0 :(得分:2)

您可以进行聚合:

SELECT Serial
       MAX(case when Section = 4 then TimeComplete end) as 'Station1',
       MAX(case when Section = 5 then TimeComplete end) as 'Station2',
       MAX(case when Section = 2 then TimeComplete end) as 'Station3',
       MAX(case when Section = 6 then TimeComplete end) as 'Station4'
FROM tableA AS a
GROUP BY Serial;