每个一对多关系ID一次SQL SUM列值

时间:2014-07-09 15:45:20

标签: sql

我有一张类似于下面的表格叫做付款。我想运行一个查询,它会给我:

付款次数,OrderAmounts的总和以及TotalPaymentAmount的总和(这里是问题)

--------------------------------------------------
| PaymentID | OrderAmount | TotalPaymentAmount   |
--------------------------------------------------
|      1    |     10      |          10          |
--------------------------------------------------
|      2    |     15      |          25          |
--------------------------------------------------
|      2    |     10      |          25          |
--------------------------------------------------
|      3    |     30      |          125         |
--------------------------------------------------
|      3    |     10      |          125         |
--------------------------------------------------
|      3    |     70      |          125         |
--------------------------------------------------
|      3    |     15      |          125         |
--------------------------------------------------

查询:

SELECT
  COUNT(PaymentID)
  ,SUM(OrderAmount)
  ,SUM(TotalPaymentAmount)
FROM Payment

这会产生:

--------------------------------------------------
| PaymentID | OrderAmount | TotalPaymentAmount   |
--------------------------------------------------
|      7    |     160     |         560          |
--------------------------------------------------

正如您所看到的,并且正如预期的那样,我们对TotalPaymentAmount列中的每个条目都进行了提交,从而产生了提升的数字。相反,我想运行相同的查询,但这一次是每个唯一的paymentID在SUM上的TotalPaymentAmount。

有什么建议吗?

永远感谢你

2 个答案:

答案 0 :(得分:3)

您需要预先汇总数据:

select sum(numpayments), sum(amount), sum(totalpayments)
from (select p.paymentid, count(*) as numpayments, sum(orderamount) as amount,
             max(TotalPaymentAmount) as totalpayments
      from payment p
      group by p.paymentid
     ) p;

答案 1 :(得分:0)

SELECT
  COUNT(PaymentID)
  ,SUM(OrderAmount)
  ,SUM(TotalPaymentAmount)
FROM Payment
group by PaymentID

我认为应该工作。