将多行排列成一行

时间:2013-11-19 19:05:12

标签: mysql

我在这里有这个代码:

SELECT t1.location AS LOCATION,
  (CASE WHEN t2.locid = '2815' THEN t2.value END) Reading,
  (CASE WHEN t2.locid = '2620' THEN t2.value END) Flw,
  (CASE WHEN t2.locid = '2618' THEN t2.value END) Prs,
  (CASE WHEN t2.locid = '2595' THEN t2.value END) Lvl

FROM table2 t2

INNER JOIN table1 t1
  ON t1.id = t2.locid

WHERE t2.t_stamp = (SELECT MAX(t2.t_stamp) 
                FROM table2 t2 
                WHERE t1.id = t2.locid)

GROUP BY t1.location

此代码已获取最新值。我只需要将它排成一行。我怎么能这样做?

我想要的输出是这样的:

LOCATION  | READING  | FLW | PRS  | LVL
east/flw  | 13.7     | 8.5 | 35.6 | 40.5

以下是示例数据,我认为在这里链接它会更容易: http://sqlfiddle.com/#!2/b05c9/1

1 个答案:

答案 0 :(得分:1)

SELECT 'east/flw' AS LOCATION, 
  ROUND(sum(CASE WHEN t2.locid = '2815' THEN t2.value ELSE 0 END), 2) AS Reading,
  ROUND(sum(CASE WHEN t2.locid = '2620' THEN t2.value ELSE 0  END), 2) AS Flw,
  ROUND(sum(CASE WHEN t2.locid = '2618' THEN t2.value ELSE 0  END), 2) AS Prs,
 ROUND( sum(CASE WHEN t2.locid = '2595' THEN t2.value ELSE 0  END), 2) AS Lvl

FROM table2 t2

INNER JOIN table1 t1
  ON t1.id = t2.locid

WHERE t2.t_stamp = (SELECT MAX(t2.t_stamp) 
                    FROM table2 t2 
                    WHERE t1.id = t2.locid)



GROUP BY 'east/flw'