【问题标题】:Transpose 1 column to a header将 1 列转置为标题
【发布时间】:2021-07-06 22:45:08
【问题描述】:

我有一个包含 4 列的表:tagid、TimeStamp、intvalue 和 floatvalue。

tagid 有四种不同类型的数据:LineRun、ScrapRun、Speed 和 Length。

每个 tagid 在 intvalue 或 floatvalue 列中都有一个值。

我想将tagid转置到header中,并插入与之关联的对应值。

你会怎么做?

我花了几个小时试图做到这一点,但没有运气! 我知道你们是专家,所以请放轻松,我是 SQL 新手 :-)

【问题讨论】:

  • 根据问题指南,请展示您尝试过的内容并告诉我们您发现了什么(在本网站或其他地方)以及为什么它不能满足您的需求。请不要使用图像作为数据,使用格式化文本。请只标记一个 RDBMS。

标签: mysql sql sql-server pivot-table


【解决方案1】:

我认为您只是在寻找 case 表达式:

select timestamp, 
       (case when tagid = 'linerun' then intvalue end) as linerun,
       (case when tagid = 'scraprun' then intvalue end) as scraprun,
       (case when tagid = 'speed' then floatvalue end) as speed,
       (case when tagid = 'length' then floatvalue end) as length
from t;

通常,目标是每个时间戳获取一行。为此,请使用聚合:

select timestamp, 
       max(case when tagid = 'linerun' then intvalue end) as linerun,
       max(case when tagid = 'scraprun' then intvalue end) as scraprun,
       max(case when tagid = 'speed' then floatvalue end) as speed,
       max(case when tagid = 'length' then floatvalue end) as length
from t
group by timestamp;

【讨论】:

  • 我明白了!...谢谢戈登。正是我想要的。你太棒了!
  • @SamSmith1986 如果它回答了你的问题,请接受它。事实上,请查看您的所有问题,看看是否有其他您可以接受的答案。
猜你喜欢
  • 2012-05-24
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多