请教SQL查询问题,高手请进,感谢!

2025-03-25 02:17:56
推荐回答(4个)
回答1:

SELECT type,typeid,code,name,(SELECT RTRIM((SELECT ' '+RTRIM(context)+' ' FROM 表名 WHERE typeid=W.typeid ORDER BY ID  FOR XML PATH ('')))) context
  FROM 表名 W
    WHERE code='000'

回答2:

select 
type,
typeid,
code,
name,
(select wm_concat(context,' ') from table_name where type=t1.type and typeid=t1.typeid) context
from table_name t1 where code=000;

至于后面context的英文顺序是无法保证了,因为表中都没有一个排序来控制。

回答3:

如果数据库支持XML的话, 可以利用XML将context组合成一个字符串,然后用replace替换掉xml标记。以SQL Server 2005或以上版本为例:

-- 定义示例表变量,并插入示例数据 
declare @tb table (id int, type nvarchar(10), typeid nvarchar(10), code nvarchar(30), name nvarchar(30), context nvarchar(30))
insert into @tb
select 1, 'A', 'A_1', '999', 'a', 'Hello'
union select 3, 'A', 'A_1', '999', 'b', '!'
union select 2, 'A', 'A_1', '000', '名称A', 'World'
-- 执行查询, 主要在replace中查询到相同的type, typeid的context值,并用for xml组合成一个字符串,然后用3个replace来替换掉xml标记,得到需要的context内容 
select s.type, s.typeid, s.code, s.name, replace(replace(replace((select v.context as T1 from @tb v where v.type = s.type and v.typeid = s.typeid order by v.id for xml path('')), '', ''), '', ''), '', '') as context
from @tb s

 执行结果如下图,

 

如果数据库比较旧,不支持XML, 那么可以自己建一个函数来实现context内容的合并。

回答4:

select 类别(type) , 类别ID(typeid) , 返回码(code) , 名称(name), 文本(context)
from table where 类别ID(typeid)=000