我有一个我感兴趣的两列的表格。
一列是日期,另一列是标记名。
我想将标记名返回到与同一日期匹配的不同列中。
我可以使用子查询来实现这一点,但有更有效的方法吗?我正在谈论检索大约20-30k行,这导致大约300,000个查询
选择插入的最有效方法是什么,以确保日期相互排列。
这是我目前的询问。 (我需要每个标记名的值在行中排成一行)
谢谢
SELECT ah1.DateTime,ah1.Value as TPH,
(select value
from dbo.AnalogHistory
where tagname = 'LS_EM1_NXG.NXG_I'
and datetime = ah1.DateTime
) as EM1_Current,
(select value
from dbo.AnalogHistory
where tagname = 'LS_EM2_NXG.NXG_I'
and datetime = ah1.DateTime
) as EM2_Current,
(select value
from dbo.AnalogHistory
where tagname = 'LS_EM1_NXG.NXG_SPEED'
and datetime = ah1.DateTime
) as EM1_Speed,
(select value
from dbo.AnalogHistory
where tagname = 'LS_EM2_NXG.NXG_SPEED'
and datetime = ah1.DateTime
) as EM2_Speed,
(select value
from dbo.AnalogHistory
where tagname = 'LS_EM1_NXG.NXG_P'
and datetime = ah1.DateTime
) as EM1_Power,
(select value
from dbo.AnalogHistory
where tagname = 'LS_EM2_NXG.NXG_P'
and datetime = ah1.DateTime
) as EM2_Power,
(select value
from dbo.AnalogHistory
where tagname = 'LS_EM1_NXG.NXG_TRQ'
and datetime = ah1.DateTime
) as EM1_Torque,
(select value
from dbo.AnalogHistory
where tagname = 'LS_EM2_NXG.NXG_TRQ'
and datetime = ah1.DateTime
) as EM2_Torque,
(select value
from dbo.AnalogHistory
where tagname = 'LS_EM1_NXG.NXG_TRQ_UTIL'
and datetime = ah1.DateTime
) as EM1_Torque_U,
(select value
from dbo.AnalogHistory
where tagname = 'LS_EM2_NXG.NXG_TRQ_UTIL'
and datetime = ah1.DateTime
) as EM2_Torque_U,
(select value
from dbo.AnalogHistory
where tagname = 'LS_TE754001G.PVAI'
and datetime = ah1.DateTime
) as EM1_NDE,
(select value
from dbo.AnalogHistory
where tagname = 'LS_TE754001H.PVAI'
and datetime = ah1.DateTime
) as EM1_DE
FROM [Runtime].[dbo].[AnalogHistory] ah1
where TagName = 'CR_WQI752010.PVAI'
and wwResolution = '600000'
and DateTime > '20160816'
and wwRetrievalMode = 'cyclic'
答案 0 :(得分:3)
也许您可以使用条件聚合。像这样:
select datetime,
max(case when tagname = 'LS_EM1_NXG.NXG_I' then value end) as val1,
. . .
from dbo.AnalogHistory
group by datetime ;
答案 1 :(得分:0)
您可以使用下面的CASE ..
select
case when tagname = 'LS_EM1_NXG.NXG_I'
and datetime = ah1.DateTime then value end as em1
--do for all tags
from
table
FROM [Runtime].[dbo].[AnalogHistory] ah1
where wwResolution = '600000'
and DateTime > '20160816'
and wwRetrievalMode = 'cyclic'
答案 2 :(得分:0)
SELECT
date(datetime) as d,
(select
group_concat(tagname)
from
dbo.AnalogHistory
where
date(datetime) = d
group by date(datetime))as res
FROM
dbo.AnalogHistory
group by date(datetime);
答案 3 :(得分:-1)
我认为你想要UNPIVOT
或PIVOT
。见worked UNPIVOT/PIVOT examples