SQL将2列值合并到行

时间:2016-06-07 21:35:21

标签: sql sql-server

我有像

这样的数据
    ID  SensorID                                Reading_Time                        Value       Type
11  A3C3EB0B-1F5E-3737-B5F7-495BFA238F88    2016-06-02 14:38:16.4980000 -04:00  24.782219   0
12  A3C3EB0B-1F5E-3737-B5F7-495BFA238F88    2016-06-02 14:38:16.4980000 -04:00  23.121845   1
13  A3C3EB0B-1F5E-3737-B5F7-495BFA238F88    2016-06-02 14:38:46.5780000 -04:00  24.77972    0
14  A3C3EB0B-1F5E-3737-B5F7-495BFA238F88    2016-06-02 14:38:46.5780000 -04:00  23.121845   1

0表示温度,1表示湿度 我没有线索 。如何编写sql以获得结果如

SensorId                             Reading_Time                       Temp      Humidity
A3C3EB0B-1F5E-3737-B5F7-495BFA238F88 2016-06-02 14:38:16.4980000 -04:00 24.782219 23.121845
A3C3EB0B-1F5E-3737-B5F7-495BFA238F88 2016-06-02 14:38:46.5780000 -04:00 24.77972  23.121845

我从这里得到2个解决方案?有没有人知道哪个更快更好?

2 个答案:

答案 0 :(得分:2)

实现此目的的一种方法是使用条件聚合,这是使其适用于任何数据库的好方法。

select sensorId,
       reading_time,
       min(case when type = 0 then value end) as Temp,
       min(case when type = 1 then value end) as Humidity
  from tbl
 group by sensorId, reading_time

答案 1 :(得分:1)

试试这个:

WITH temperature (sID, rTime, temp)
AS (SELECT sensorid, reading_time, value FROM data_table WHERE type=0)
SELECT sensorid, reading_time, temp, value as humidity
FROM data_table JOIN temperature ON sensorid=sID AND reading_time=rTime
WHERE type=1

<强>解释

  • WITH创建所有温度行的温度临时表
  • 按时间和传感器列出JOIN
  • 从每个传感器时间对中选择临时表的温度和原始表中的湿度