sql中如何多查一列出来

select (select itemval from plat.pf45 where typeid = 'housetype' and P_LEVEL = '2' and itemid = b.housetype) , count(1) from ln003 a, ln014 b where a.loancontrcode = b.loancontrcode group by b.housetype

这个sql没有问题
结果是 itemval count 这两列
我想把pf45这个表中 SYSTEMID 这一列也类出来
SYSTEMID itemval count 这三列 应该怎么写呢
select (select SYSTEMID ,itemval from plat.pf45 where typeid = 'housetype' and P_LEVEL = '2' and itemid = b.housetype) , count(1) from ln003 a, ln014 b where a.loancontrcode = b.loancontrcode group by b.housetype
这样不行

这样试试:


select (select SYSTEMID from plat.pf45 where typeid = 'housetype' and P_LEVEL = '2' and itemid = b.housetype) , (select itemval from plat.pf45 where typeid = 'housetype' and P_LEVEL = '2' and itemid = b.housetype) ,count(1) from ln003 a, ln014 b where a.loancontrcode = b.loancontrcode group by b.housetype

你的写法不行,是因为select列中的子查询只能查询单个字段作为结果值,不能查询多个字段。
可以这么写,用两个子查询:

select 
(select SYSTEMID from plat.pf45 where typeid = 'housetype' and P_LEVEL = '2' and itemid = b.housetype) SYSTEMID, 
(select itemval from plat.pf45 where typeid = 'housetype' and P_LEVEL = '2' and itemid = b.housetype) itemval, 
count(1) 
from ln003 a, ln014 b where a.loancontrcode = b.loancontrcode 
group by b.housetype

你既然要查这个表里的多个字段,为什么不直接关联,非得写到字段的子查询里去?

select p.SYSTEMID, p.itemval, count(1)
  from ln003 a, ln014 b, plat.pf45 p
 where a.loancontrcode = b.loancontrcode
   and p.typeid = 'housetype'
   and p.P_LEVEL = '2'
   and p.itemid = b.housetype
 group by p.SYSTEMID, p.itemval
;

当然前提是 plat.pf45这个表里的数据是全的,如果不全,改为左连接就行了

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632