【问题标题】:SQL merge separate time stamps into 1 row per serial numberSQL 将单独的时间戳合并为每个序列号 1 行
【发布时间】: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


【解决方案1】:

你可以做聚合:

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;

【讨论】:

  • 这确实有效。我会花几分钟看看有什么/如果有其他想法出现,然后再检查一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-21
  • 2013-07-29
  • 1970-01-01
  • 2016-06-06
相关资源
最近更新 更多