sqlserver 这个分组查询问题?

id num(车次) station(车站)
2 k339 北京
3 k339 秦皇岛
4 k339 沈阳
5 k339 哈尔滨
6 t109 北京
7 t109 无锡
8 t109 上海

现在要查询:查询每班车次所经过的站点
好像是让num这一列分组查询,查询出来的结果应该是这样的:

K339:北京 秦皇岛 沈阳 哈尔滨
T109:北京 无锡 上海
我说的是把我写的结果一口气查出来,不是一条一条查,要不然我还问啊!

第1个回答  2009-07-19
select num '车次',station '车站' from 表名 group by num;本回答被提问者采纳
第2个回答  2009-07-19
从你的结果来看,这个SQL是属于列行转置,你无法确定[车站]一共要设置几个字段,一般来说只有行列转置是合理的。

如果你的结果就是展现结果,你可以通过程序来展示,如果要用SQL来展示,可以用存储过程或者游标
将select num,station from t where num=@num的值进行拼装
第3个回答  2009-07-19
create function f_ret(@num varchar(50))
returns varchar(8000)
as
begin
declare @station varchar(8000),@id int
select @station=''
declare cur cursor for select id from z where num=@num
open cur
fetch next from cur into @id
while @@fetch_status=0
begin
select @station=@station+station+' ' from z where id=@id and num=@num
fetch next from cur into @id
end
close cur
deallocate cur
return @station
end

go

select distinct num,dbo.f_ret(num) as station from z

把表名改改就可以用了
第4个回答  2009-07-19
USE (数据库名)

SELECT station FROM (表名) WHERE num=“k339”
t109如上所示
第5个回答  2009-07-19
这个也只能像 ytbelwxg一样用游标了,一个SQL恐怕是不得行的.
相似回答