从单列查询单独的值

时间:2016-10-13 04:29:15

标签: sql sql-server sql-server-2008

Click Show Picture

SELECT 
    [Date_Time],
    [TagID],
    [Value_Per_15min]
FROM 
    [RIDTL].[dbo].[Rawdata]
WHERE 
    Date_Time BETWEEN '01-09-2016 00:00:00:000' AND '2016-10-12 23:59:59:000'  
ORDER BY 
    Date_Time

我想要输出:

Output Picture

1 个答案:

答案 0 :(得分:0)

假设您想要选择TagID的前两个值,分别对应Date_TimeValue_Per_15min列。

SELECT [Date_Time],[1] TagID1,[2] TagID2,[Value_Per_15min]
FROM
(SELECT 
    [Date_Time],
    [TagID],
    [Value_Per_15min],
    ROW_NUMBER()OVER(PARTITION BY [Date_Time],[Value_Per_15min] ORDER BY [TagID]) CNT
FROM [RIDTL].[dbo].[Rawdata]
WHERE  Date_Time BETWEEN '01-09-2016 00:00:00:000' AND '2016-10-12 23:59:59:000')t
PIVOT
(MIN(TagID)
 FOR CNT IN ([1],[2]))piv;