关于sql中sum(),group by 语句的修改,要添加一个查询列而不改变查询结果。具体看正文。
以下是我要修改的查询语句。是按照cinventoryid进行汇总计算的。selectsum(nnumber)num,sum(coalesce(nmoney,0))mny,...
以下是我要修改的查询语句。是按照 cinventoryid 进行汇总计算的。
select sum(nnumber) num,
sum(coalesce(nmoney, 0)) mny,
cinventoryid
from h, b
where h.id = b.id
and h.dr = 0
and b.dr = 0
AND b.cbill_bid in (select id from ia)
group by cinventoryid
现在想要增加一列显示名称:dep.name。对应关系为 dep.pk_dep = h.depid.
我修改了查询语句为:
select sum(nnumber) num,
sum(coalesce(nmoney, 0)) mny,
cinventoryid,
dep.deptname
from h, b, dep
where h.id = b.id
and h.dr = 0
and b.dr = 0
AND b.cbill_bid in (select id from ia)
and dep.pk_dep = h.depid
group by cinventoryid, dep.deptname
这样虽然显示出了名称,但是求和的计算出现问题。原本应该是1条的数据,被拆分成多条。
个人认为是因为后面的 group by 汇总出现问题,可是我不知道怎么改。哪位高手能帮忙修改下?不胜感激。 展开
select sum(nnumber) num,
sum(coalesce(nmoney, 0)) mny,
cinventoryid
from h, b
where h.id = b.id
and h.dr = 0
and b.dr = 0
AND b.cbill_bid in (select id from ia)
group by cinventoryid
现在想要增加一列显示名称:dep.name。对应关系为 dep.pk_dep = h.depid.
我修改了查询语句为:
select sum(nnumber) num,
sum(coalesce(nmoney, 0)) mny,
cinventoryid,
dep.deptname
from h, b, dep
where h.id = b.id
and h.dr = 0
and b.dr = 0
AND b.cbill_bid in (select id from ia)
and dep.pk_dep = h.depid
group by cinventoryid, dep.deptname
这样虽然显示出了名称,但是求和的计算出现问题。原本应该是1条的数据,被拆分成多条。
个人认为是因为后面的 group by 汇总出现问题,可是我不知道怎么改。哪位高手能帮忙修改下?不胜感激。 展开
1个回答
展开全部
加一个DISTINCT看看。。。。。。
select distinct dep.deptname,cinventoryid,sum(nnumber) num,sum(coalesce(nmoney, 0)) mny
from h, b, dep
where h.id = b.id
and h.dr = 0
and b.dr = 0
AND b.cbill_bid in (select id from ia)
and dep.pk_dep = h.depid
group by cinventoryid, dep.deptname
看着有点乱,涉及3个表为什么不用连接。。。。
select distinct dep.deptname,cinventoryid,sum(nnumber) num,sum(coalesce(nmoney, 0)) mny
from h, b, dep
where h.id = b.id
and h.dr = 0
and b.dr = 0
AND b.cbill_bid in (select id from ia)
and dep.pk_dep = h.depid
group by cinventoryid, dep.deptname
看着有点乱,涉及3个表为什么不用连接。。。。
追问
distinct 这个是取消重复值的吧? 连接的话,这个语句是别人写的,我不太会用连接,怕有什么影响。可以的话帮我改一下好吗?用连接的方式
追答
最好给一下表,给几个测试数据,然后你写个结果,这样写起来有目的性,现在我根本不知道你表的结构和目标
slelecct distinct dep.deptname,h.cinventoryid,sum(b.nnumber) num,sum(coalesce(b.nmoney, 0)) mny
--不知道表,前缀胡乱写的,自己改下
from dep d
inner join h on d.pk_dep=h.depid
inner join b on (h.id = b.id and h.dr = b.dr)
where b.dr=0 and b.cbill_bid in (select id from ia)
group by cinventoryid, dep.deptname
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询