合并具有不同过滤器的列

时间:2018-11-30 18:50:20

标签: sql sql-server

我基本上有一个大型数据库,其中包含[t_stamp],[floatvalue]和[tagpath]列。我试图最终能够只用[t_stamp],以不同的[tagpath]值排序的[floatvalue]的多列进行查询。我不是将行变成列。我正在用不同的过滤复制一列。据我所知,不涉及任何枢纽。如果这令人困惑,我真的很抱歉,所以我一定会添加表格图片。 我认为这将是一个完美案例,其中每个列都可以简单地对标签路径进行过滤,但是当我尝试执行此操作时,我得到了[t_stamp]的多个结果,其中包括一个相当慢的sql查询,仅执行两种情况。 (最终将需要做15到20,但是一旦确定查询时间就不会成为考虑因素了)

select distinct
[t_stamp] as 'Time',
(case when dbo.taghistoriancombined.tagpath like 'extruder 1/plc/temps/exhaust wet bulb temp' then [floatvalue] end) as 'Wet Bulb',
(case when dbo.taghistoriancombined.tagpath like 'extruder 1/plc/extruder/motor load' then [floatvalue] end) as 'Motor Load'
from [dbo].[TagHistorianCombined]

然后我想,“好吧,我可以只用空占位符进行两个查询,并使用一个联合来消除任何可能的覆盖。

SELECT
[t_stamp] as time
,[floatvalue] as 'Motor Load'
,null as 'Wet Bulb'
FROM [dbo].[TagHistorianCombined]
where tagpath like 'extruder 1/plc/extruder/motor load'
 union
SELECT
[t_stamp] as time
,null as 'Motor Load'
,[floatvalue] as 'Wet Bulb'
FROM [dbo].[TagHistorianCombined]
where tagpath like 'extruder 1/plc/temps/exhaust wet bulb temp'
order by time desc

但是不幸的是,这给了我相同的结果。 Desired Schema but Undesired Results

解决此问题的最佳方法是什么?我现在的讲解技巧很粗糙,这是我在本网站上的第一篇文章,因此,如果我错过了任何内容,或者需要进一步解释,请随时询问。

1 个答案:

答案 0 :(得分:0)

我认为您想要group by。以下每个时间戳返回一行:

select t_stamp,
       max(case when thc.tagpath like 'extruder 1/plc/temps/exhaust wet bulb temp' then floatvalue end) as WetBulb,
       max(case when thc.tagpath like 'extruder 1/plc/extruder/motor load' then floatvalue end) as MotorLoad
from [dbo].TagHistorianCombined thc
where thc.tagpath like 'extruder 1/plc/temps/exhaust wet bulb temp' or
      thc.tagpath like 'extruder 1/plc/extruder/motor load'
group by t_stamp