我有一个表scott2
,我从中运行两个查询。
第一个查询是:
SELECT rateid, sysuserid, appraiserid, category, rate FROM `scott2` WHERE sysuserid = appraiserid and sysuserid = '20' group by category order by category;
其结果是:
第二个是:
SELECT rateid, sysuserid, appraiserid, category, sum(rate) FROM `scott2` WHERE sysuserid != appraiserid and sysuserid = '20' group by category order by category asc;
其结果是:
我想将结果合并为以下格式。我希望查询2中的sumrate
列与查询1中的rate
列相邻。
SYSUSERID |类别| RATE |求和
我尝试过使用此子查询,但无济于事。
SELECT sysuserid, category,
(SELECT rate FROM `scott2` WHERE sysuserid = appraiserid and sysuserid = '20' group by category order by category asc) as 'rate',
(select sum(rate) from scott2 where sysuserid != appraiserid and sysuserid = '20' group by category order by category asc) as 'sumrate'
from scott2
group by category
order by category asc;
错误:
子查询返回1行以上
我如何实现自己想要的?
答案 0 :(得分:3)
在主查询中,您未在其中指定“ sysuserid = 20”,并且使用的是无效的“ sysuserid ='20'”。同样,当您在主查询中使用“按类别分组”时,您应该在条件od子查询所在的位置进行分类。
要限制子查询第二项仅包含一个结果,可以使用limit。虽然限制无效。您应该在逻辑上验证“ sysuserid” +“ category”组合的唯一结果。
您可以尝试以下查询。
SELECT sysuserid, category,
(SELECT sc_i.rate FROM `scott2` as sc_i WHERE sc_i.sysuserid = sc_i.appraiserid and sc_i.sysuserid = sc.sysuserid and sc_i.category = sc.category limit 1) as 'rate',
(SELECT sc_i.rate FROM `scott2` as sc_i WHERE sc_i.sysuserid <> sc_i.appraiserid and sc_i.sysuserid = sc.sysuserid and sc_i.category = sc.category limit 1) as 'sumrate'
from scott2 as sc
where sysuserid = 20
group by sysuserid, category
order by category asc;
答案 1 :(得分:1)
尝试此代码
SELECT t1.sysuserid, t1.category, t1.rate ,
(select sum(rate) from scott2 t2 where t2.category = t1.category AND sysuserid != appraiserid and sysuserid = '20' group by category) as sumrate
from scott2 t1
group by t1.category
order by t1.category asc;