注册 登录
编程论坛 SQL Server论坛

求一个select语句的问题

darlingpeng 发布于 2012-02-15 16:46, 1053 次点击
我的问题是这样的:
比如有表:t_temp,有字段:f_pole,f_layer,f_temp。即杆、层、温度。
3个字段有如下值:
1,1,11
1,2,21
1,3,31
1,4,41
2,1,12
2,2,22
2,3,32
2,4,42
3,1,13
3,2,23
3,3,33
3,4,43
......
怎么输出如下表样式内容:
1,11,21,31,41
2,12,22,32,42
3,13,23,33,43
......
即把原同一杆的不同层的温度显示在一行。谢谢

我还想不出有什么办法,请大家帮忙!!!
11 回复
#2
png2012-02-16 00:04
类似 -
select    f_pole,
          max(case when f_layer = 1 then f_temp end),
          max(case when f_layer = 3 them f_temp end)
from      t_temp
group by  f_pole


或查看 PIVOT 用法

#3
darlingpeng2012-02-16 08:38
谢谢png。
我根据你的思路再想一下。
#4
darlingpeng2012-02-16 09:25
select * from
(
select f_pole,
case when f_layer=1 then f_temp end as tmp1,
case when f_layer=2 then f_temp end as tmp2,
case when f_layer=3 then f_temp end as tmp3
case when f_layer=4 then f_temp end as tmp4 from t_poletest
)t

这样可以产生结果,但不对,关键是不能group by f_pole。我就是需要以f_pole分组。
tmp1,tmp2,tmp3这3列怎么在group by语句中添加?
#5
darlingpeng2012-02-16 09:28
select * from
(
select f_pole,
case when f_layer=1 then f_temp end as tmp1,
case when f_layer=2 then f_temp end as tmp2,
case when f_layer=3 then f_temp end as tmp3
case when f_layer=4 then f_temp end as tmp4 from t_poletest
)t

这样可以产生结果,但不对,有一些不是值的多余的NULL。关键是不能group by f_pole。我就是需要以f_pole分组。
tmp1,tmp2,tmp3,tmp4这4列怎么在group by语句中添加?
#6
darlingpeng2012-02-16 09:32
group by f_pole,tmp1,tmp2,tmp3,tmp4这样可以,但结果不对。
就是上面说的,有一些多余的不是值的NULL。
#7
darlingpeng2012-02-16 09:38
我只是想以f_pole分组,而group by语句中加了tmp1,...意思就就不对了。
#8
png2012-02-16 22:45
你没试下我写的语句?
#9
darlingpeng2012-02-17 14:55
试过,但信息不全,因为只是求了max。除非有条件。
#10
tangyunzhong2012-02-17 17:44
回复 楼主 darlingpeng
你这个问题解决办法是用行列旋转的,上面的方法都只是都对你起例数据回答,
,,,
#11
png2012-02-17 22:29
回复 9楼 darlingpeng
你是说得不到这样的结果?

1,11,31
2,12,32
3,13,33
#12
xun1232012-02-19 21:15
不错
1