0

我有一张桌子:

CityID     ParamName      ParamValue
------    -----------     ----------
  1       Temperature        23    
  1       Humidity           56
  2       Temperature        27
  2       Humidity           49

我想创建一个视图,如下所示:

CityID    Temperature     Humidity
------    -----------     --------
  1          23              56
  2          27              49

我的数据库引擎是 MySQL。

有人可以帮我定义这样的观点吗?任何帮助将不胜感激。

4

2 回答 2

1

MySQL 没有PIVOT函数,所以你需要给你一个CASE声明:

SELECT CityId,
    SUM(CASE WHEN ParamName = 'Temperature' THEN ParamValue END) Temperature,
    SUM(CASE WHEN ParamName = 'Humidity' THEN ParamValue END) Humidity
FROM yourTable
GROUP BY CityId

请参阅带有演示的 SQL Fiddle

于 2012-08-03T17:26:26.903 回答
0

就像是

select someTable.CityID,temps.ParamValue as Temperature,Hums.ParamValue as Humidity
From SomeTable
inner join someTable temps 
On someTable.CityID = temps.CityID and temps.ParamName = 'Temperature'
inner join SomeTable hums  
On someTable.CityID = hums.CityID and hums.ParamName = 'Humidity'
于 2012-08-03T17:30:29.127 回答