"子查询返回的值多于一个" 问题的处理

longshujun 2008-07-04 02:22:40
要把子查询的多行查询结果放到主查询结果中的一行中的一个字段中来 如 “张三 高血压、糖尿病” 请问怎么写,下面的语句就有问题:
select a.hzxm as 姓名,诊断=(select zdmc from ZY_BRZDQK where syxh=a.syxh and zdlb=2 and zdlx=1) from ZY_BRSYK a (nolock) where a.blh='100'

请问大家应该怎样写语句?用游标+临时表吗?
...全文
193 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
longshujun 2008-10-14
  • 打赏
  • 举报
回复
已经按照 wgzaaa 的方法写了一个函数实现了,非常感谢大家!
hery2002 2008-07-04
  • 打赏
  • 举报
回复
[Quote=引用 13 楼 wgzaaa 的回复:]
看来和尚是患戒了
[/Quote]
主要是他开始没有说清楚,
按照提示错误,
直接top 或者max min就可以解决了,
后来他说要一个结果集,
所以后面7,8楼贴了相应的处理方式,
吼吼~
wgzaaa 2008-07-04
  • 打赏
  • 举报
回复
看来和尚是患戒了
wgzaaa 2008-07-04
  • 打赏
  • 举报
回复
--先创建合并函数
create function fun_zdmc(@syxh varchar(200)) returns varchar(2000) as
begin
declare @str varchar(2000)
set @str=''
select @str=@str+'、'+zdmc from ZY_BRZDQK where syxh=@syxh and zdlb=2 and zdlx=1
return stuff(@str,1,1,'')
end

--再改成下面的样子
select a.hzxm as 姓名,诊断=dbo.fun_zdmc(a.syxh) from ZY_BRSYK a (nolock) where a.blh='100'
hanjs 2008-07-04
  • 打赏
  • 举报
回复
“张三 高血压、糖尿病”

这回知道,让和尚误导了,上来就看语句了!!
hanjs 2008-07-04
  • 打赏
  • 举报
回复
用外联结!!
ojuju10 2008-07-04
  • 打赏
  • 举报
回复

需要写个合并函数,才可以解决楼主的问题!
hery2002 2008-07-04
  • 打赏
  • 举报
回复
或者说写个函数.
参考:
合并分拆表_整理贴1
http://topic.csdn.net/u/20080612/22/c850499f-bce3-4877-82d5-af2357857872.html
hery2002 2008-07-04
  • 打赏
  • 举报
回复
declare @str nvarchar(200),@syxh nvarchar(200)
set @str =''
select @str = @str +zdmc +',' from ZY_BRZDQK where syxh=@syxh and zdlb=2 and zdlx=1
select a.hzxm as 姓名,诊断= @str from ZY_BRSYK a (nolock) where a.blh='100'
hery2002 2008-07-04
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 happyflystone 的回复:]
和尚,全让你说了
[/Quote]
关键好像不是这个意思,
hery2002 2008-07-04
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 longshujun 的回复:]
我是要所有的结果都取出来, top 1和max(zdmc)都只有一条记录了;可能只能先建临时表,然后使用游标或者数组可以实现
[/Quote]
那就不能那样使用子查询,
使用left join 等关联方式?
-狙击手- 2008-07-04
  • 打赏
  • 举报
回复
和尚,全让你说了
longshujun 2008-07-04
  • 打赏
  • 举报
回复
我是要所有的结果都取出来, top 1和max(zdmc)都只有一条记录了;可能只能先建临时表,然后使用游标或者数组可以实现
hery2002 2008-07-04
  • 打赏
  • 举报
回复
select a.hzxm as 姓名,诊断=(select max(zdmc) from ZY_BRZDQK where syxh=a.syxh and zdlb=2 and zdlx=1) from ZY_BRSYK a (nolock) where a.blh='100'
hery2002 2008-07-04
  • 打赏
  • 举报
回复
select a.hzxm as 姓名,诊断=(select top 1 zdmc from ZY_BRZDQK where syxh=a.syxh and zdlb=2 and zdlx=1) from ZY_BRSYK a (nolock) where a.blh='100' 

22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧