27,579
社区成员
发帖
与我相关
我的任务
分享
--如查询出分数大于50的科目,用一行显示,中间用分号显示
CREATE TABLE TAB
(
stu_score float,
stu_subject varchar(10)
)
INSERT INTO TAB
SELECT 80,'语文' UNION
SELECT 60,'数学' UNION
SELECT 50,'英语'
CREATE TABLE TAB
(
stu_score float,
stu_subject nvarchar(10)
)
INSERT INTO TAB
SELECT 80,N'语文' UNION
SELECT 60,N'数学' UNION
SELECT 50,N'英语'
declare @s nvarchar(500)
select @s=isnull(@s+',','')+stu_subject
from tab
where stu_score>50
select @s
drop table tab
SELECT (SELECT stu_subject+';' FROM TAB WHERE stu_score>50 FOR XML PATH('')) AS p
select stuff((select ','+stu_subject
from tab
where stu_score>50
for xml path('')),1,1,'')
drop table tab
select
stuff((select ','+stu_subject from tab where stu_score >= 50 for xml path('')),1,1,'') as p
--如果还要其他的数据用 union all 再去 select 注意where的条件。
CREATE TABLE TAB
(
stu_score float,
stu_subject varchar(10)
)
INSERT INTO TAB
SELECT 80,'语文' UNION
SELECT 60,'数学' UNION
SELECT 50,'英语'
SELECT stuff((SELECT ';'+stu_subject FROM TAB WHERE stu_score>50 FOR XML PATH('')),1,1,'')
/*
---------
数学;语文
select
stuff((select ','+stu_subject from tab where stu_score>50 for xml path('')),1,1,'')
/**
------------------------------------------------------
数学,语文
(1 行受影响)
**/
select
stuff((select ','+stu_subject from tab where stu_score>=60 for xml path('')),1,1,'')