日期:2014-05-18  浏览次数:20423 次

sql 语句怎么写! 有点麻烦
select * from t_source_question_kp

qid kp_id
1 121
1 122
1 124
4 1097
4 1096
2 3

现在需要将qid=1的kp_id字段值查到
select kp_id from t_source_question_kp where qid=1
kp_id
121
122
124

但是需要将kp_id字段值放在一起显示 如这样:
select kp_id from t_source_question_kp where qid=1
kp_id
121 122 124

这样sql语句怎么写 页面代码已经固定 现在只能改sql语句了

------解决方案--------------------
SQL code
if object_id('[t_source_question_kp]') is not null drop table [t_source_question_kp]
go
create table [t_source_question_kp] (qid int,kp_id int)
insert into [t_source_question_kp]
select 1,121 union all
select 1,122 union all
select 1,124 union all
select 4,1097 union all
select 4,1096 union all
select 2,3

select * from [t_source_question_kp]


alter FUNCTION dbo.f_str(@id int) 
RETURNS varchar(8000) 
AS 
BEGIN 
    DECLARE @r varchar(8000) 
    SET @r = '' 
    SELECT @r = @r +' '+ convert(varchar,kp_id) FROM t_source_question_kp WHERE qid=@id 
    RETURN STUFF(@r, 1, 1, '') 
END 
GO 

select qid,dbo.f_str(qid) as  kp_id from t_source_question_kp group by qid

/*
1    121 122 124
2    3
4    1097 1096*/