2016-08-20 60 views
2

我有兩列的表我很感興趣。返回SQL數據爲多列

一個欄是日期,而另一個是標記名。

我想將標記名返回到與相同日期匹配的不同列中。

我可以實現這個使用子查詢,但是有沒有一個更有效的方式來做到這一點?我在說的是檢索大約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' 

回答

3

也許你可以使用條件的聚集。事情是這樣的:

select datetime, 
     max(case when tagname = 'LS_EM1_NXG.NXG_I' then value end) as val1, 
     . . . 
from dbo.AnalogHistory 
group by datetime ; 
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' 
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);