您的位置:首页 > 数据库

数据库查询-行列转换的问题

2005-02-18 12:13 302 查看
现在数据库中有如下结构的表:
----------------------------------------------------------------
城市| 日期 |温度| --------------------------------------
长沙|2004-12-21| 23 | ---------------------------------------
湘潭|2004-12-21| 28 | ---------------------------------------
株洲|2004-12-21| 26 | ---------------------------------------
长沙|2004-12-22| 27 | ---------------------------------------
湘潭|2004-12-22| 25 | ---------------------------------------
株洲|2004-12-22| 22 | ---------------------------------------

查询结果显示为:
-----------------------------------------------------------------
日期 |长沙|湘潭|株洲|
-----------------------------------------------------------------
2004-12-21| 23 | 28 | 26 | ----------------------------------
2004-12-22| 27 | 25 | 22 | ----------------------------------

如果知道城市个数
select 日期,
[长沙]=max(case 城市 when '长沙' then 温度 else 0 end),
[湘潭]=max(case 城市 when '湘潭' then 温度 else 0 end),
[株洲]=max(case 城市 when '株洲' then 温度 else 0 end)
from 表
group by 日期
order by 日期

--如果不知道是几个城市, 就用下面第二个语句
delcare @s varchar(8000)

set @s='select 日期 '
select @s=@s+',['+城市+']=max(case 城市 when '''+城市+''' then 温度 else 0 end)'
from 表 group by 城市
set @s=@s+' from 表 group by 日期'

exec(@s)

其中使用max主要是为了使用group by
摘自csdn(lsxaa(小李铅笔刀)等帖子)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: