SQL使用group by计算多行

时间:2015-02-23 12:55:36

标签: sql group-by sum

我正在使用以下查询来概述我的结果。此时查询显示4个不同的行而不是2.我希望前3列作为查询的键。建议这样做?

select 
    r.ID, m.MATERIALID, m.LOT, ms.AMMOUNT as aantal, 
    m.NETPRICE as prijs, 
    (ms.AMMOUNT * m.NETPRICE) as Total 
from 
    rc_recall r 
inner join 
    RC_RECALLMATSTORE ms on r.ID = ms.RECALLID 
inner join 
    RC_RECALLMATERIAL m ON ms.RECALLID = m.RECALLID and ms.LINE = m.LINE 
where 
    r.ID = '2015073' and d.LANG = 'FR'
group by 
    r.ID, m.MATERIALID m.LOT, ms.AMMOUNT, m.NETPRICE;

我得到的结果:

2015073 | 100654643 | 1 | 2 | 0.9200    | 1.8400000
2015073 | 100654643 | 1 | 5 | 0.9200    | 4.6000000
2015073 | 100654643 | 2 | 3 | 0.9200    | 2.7600000
2015073 | 100654643 | 2 | 5 | 0.9200    | 4.6000000

是否可以使用相同的行计算:'r.ID,m.MATERIALID,m.LOT'彼此?

我想要的结果:

2015073 | 100654643 | 1 | 7 | 0.9200    | 6.4400000
2015073 | 100654643 | 2 | 8 | 0.9200    | 7.3600000

3 个答案:

答案 0 :(得分:2)

删除" ms.AMMOUNT"从您的GROUP BY和添加一些SUM()函数应该做的工作:

select r.ID, m.MATERIALID, m.LOT
        , SUM(ms.AMMOUNT) as aantal
        , m.NETPRICE as prijs
        , SUM(ms.AMMOUNT * m.NETPRICE) as Total
from rc_recall r 
inner join RC_RECALLMATSTORE ms on r.ID = ms.RECALLID 
inner join RC_RECALLMATERIAL m ON ms.RECALLID = m.RECALLID and ms.LINE = m.LINE 
where r.ID = '2015073' and d.LANG = 'FR'
group by r.ID, m.MATERIALID, m.LOT, m.NETPRICE;

答案 1 :(得分:1)

如果您不想按AMMOUNT和NETPRICE分组,则必须以其他方式聚合它们,例如MIN或SUM。这将返回您在上面描述的输出,但您需要确认它是否真正正确;

select r.ID, m.MATERIALID, m.LOT, ms.AMMOUNT as aantal, min(m.NETPRICE) as prijs, sum(ms.AMMOUNT * m.NETPRICE) as Total 
from rc_recall r 
inner join RC_RECALLMATSTORE ms on r.ID = ms.RECALLID 
inner join RC_RECALLMATERIAL m ON ms.RECALLID = m.RECALLID and ms.LINE = m.LINE 
where r.ID = '2015073' and d.LANG = 'FR'
group by r.ID, m.MATERIALID m.LOT;

答案 2 :(得分:0)

您可能希望使用sum()和其他聚合函数:

select r.ID, m.MATERIALID, m.LOT, sum(ms.AMMOUNT) as aantal,
       sum(m.NETPRICE )as prijs, sum(ms.AMMOUNT * m.NETPRICE) as Total
from rc_recall r inner join
     RC_RECALLMATSTORE ms
     on r.ID = ms.RECALLID inner join
     RC_RECALLMATERIAL m
     ON ms.RECALLID = m.RECALLID and ms.LINE = m.LINE 
where r.ID = '2015073' and d.LANG = 'FR'
group by r.ID, m.MATERIALID, m.LOT;

您还需要将group by修复为正确的粒度。