2016-08-20 28 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);