和结果乘以行数

时间:2017-03-02 05:37:08

标签: sql sql-server sql-server-2008

我正在尝试从我的表中获得2笔款项,一张是订购商品的表格,另一张是收到商品的表格。根据我当前的查询,我得到的是2014年的总和,从106(我想得到的实际总和)乘以19(记录数)

select POD.PO_No, SUM(POD.Qty) as Qty, RRD.RR_No, SUM(RRD.QtyRcvd) as QtyReceived
from tbl_PODetail POD inner join tbl_RRDetail RRD on POD.PO_No = RRD.PO_Reference
where POD.PO_No = 'PO-000001'
group by POD.PO_No, RRD.RR_No

导致这种情况的原因以及如何纠正?

样本表

PO No      | Item   | Qty
-------------------------
PO-0000001 | Item A | 5
PO-0000001 | Item B | 7
PO-0000001 | Item B | 3

RR No      | Item   | Qty | PO_Reference
----------------------------------------
RR-0000001 | Item A | 5   | PO-0000001
RR-0000001 | Item B | 7   | PO-0000001
RR-0000001 | Item B | 3   | PO-0000001

预期产出:

PO No      | Qty | RR No      | Qty Rcvd
-----------------------------------------
PO-0000001 | 15  | RR-0000001 |  15

我得到了什么

PO No      | Qty | RR No      | Qty Rcvd
-----------------------------------------
PO-0000001 | 45  | RR-0000001 |  45

4 个答案:

答案 0 :(得分:1)

您错过了加入时的POD.Item = RRD.Item,这就是您获得成倍记录的原因。

select POD.PO_No, SUM(POD.Qty) as Qty, RRD.RR_No, SUM(RRD.QtyRcvd) as QtyReceived
from tbl_PODetail POD 
inner join tbl_RRDetail RRD on POD.PO_No = RRD.PO_Reference and POD.Item = RRD.Item
where POD.PO_No = 'PO-000001'
group by POD.PO_No, RRD.RR_No

答案 1 :(得分:0)

这个答案反映了我对你的问题的理解。您似乎希望通过采购订单编号汇总tbl_PODetail并将总和计算为数量。然后,您希望将第二个表tbl_RRDetail聚合两列,并将第一个聚合结果加入到仅使用PO编号的结果中。如果这是正确的,那么一种方法是使用两个单独的子查询进行聚合并将它们连接在一起。

WITH cte1 AS (
    SELECT RR_No, PO_Reference, SUM(QtyRcvd) AS QtyReceived
    FROM tbl_RRDetail
    GROUP BY RR_No, PO_Reference
),
WITH cte2 AS (
    SELECT PO_No, SUM(Qty) AS Qty
    FROM tbl_PODetail
    GROUP BY PO_No
)
SELECT t2.PO_No, t2.Qty, t1.RR_No, t1.QtyReceived
FROM cte1 t1
INNER JOIN cte2 t2
    ON t1.PO_Reference = t2.PO_No
WHERE t1.PO_No = 'PO-000001'

答案 2 :(得分:0)

尝试聚合子查询中的值并在之后加入它们

Select *
From (
  Select po_no, sum(qty) qty
  From tbl_PODetail
  Group by po_no
) p join (
  Select rr_no, po_reference, sum(qty) qty_rcvd
  From tbl_RRDetail
  Group by rr_no, po_reference
) r on p.po_no = r.po_reference
Where p.po_no = 'PO-0000001'

答案 3 :(得分:0)

也试试这个。希望这可以提供帮助。

        select * into #table1   from (                 
select 'PO-0000001' as PO_No,'Item A' as Item,5 as QTY union
select 'PO-0000001' as PO_No,'Item B' as Item,7 as QTY union 
select 'PO-0000001' as PO_No,'Item C' as Item,3 as QTY
)t

select * into #table2 from (
select 'RR-0000001' as RR_No,'Item A' as Item,5 as QTY,'PO-0000001' as PO_Referrence union
select 'RR-0000001' as RR_No,'Item B' as Item,7 as QTY,'PO-0000001' as PO_Referrence union
select 'RR-0000001' as RR_No,'Item C' as Item,3 as QTY,'PO-0000001' as PO_Referrence 
)t

select t1.PO_No,sum(t2.qty) as 'Qty' ,t2.RR_no,sum(t1.qty) as 'QTY Rcvd'
from #table1 t1
inner join #table2 t2
on t1.PO_no=t2.PO_Referrence and t1.item=t2.item
group by t1.PO_No,t2.RR_no