【发布时间】:2019-06-23 22:30:37
【问题描述】:
我的 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
【问题讨论】:
-
@a_horse_with_no_name 微软服务器,对不起,应该提到的。
-
如果
timestamp值的数量在不同的SerialNumber值之间不同会怎样?这种类型的数据透视最好在您的表示层中完成,而不是在查询中。
标签: sql sql-server tsql timestamp pivot