两个表中的SQL sum和group值

时间:2016-02-03 12:46:00

标签: sql

我正在尝试根据卖家的名字对销售数据进行分组。该名称可在另一个表中找到。我的表看起来像这样:

InvoiceRow:

+-----------+----------+-----+----------+
| InvoiceNr | Title    | Row |  Amount  |
+-----------+----------+-----+----------+
|  1        | Chair    |  1  |  2000.00 |
|  2        | Sofa     |  1  |  1500.00 |
|  2        | Cushion  |  2  |  2000.00 |
|  3        | Lamp     |  1  |  6500.00 |
|  4        | Table    |  1  |  -500.00 |
+-----------+----------+-----+----------+

InvoiceHead:

+-----------+----------+------------+
| InvoiceNr | Seller   | Date       |
+-----------+----------+------------+
|  1        | Adam     | 2016-01-01 |
|  2        | Lisa     | 2016-01-04 |
|  3        | Adam     | 2016-01-08 |
|  4        | Carl     | 2016-01-17 |
+-----------+----------+------------+

我正在使用的查询目前如下所示:

SELECT SUM(Amount)
FROM InvoiceRow
WHERE InvoiceNr IN (
  SELECT InvoiceNr
  FROM InvoiceHead
  WHERE Date >= '2016-01-01' AND Date < '2016-02-01'
)

这适用于1月份所有发票(总销售额)的所有行的值。

我想要做的是按每个卖家的名字分组的销售摘要。这样的事情:

+----------+------------+
| Seller   | Amount     |
+----------+------------+
| Adam     | 8500.00    |
| Lisa     | 3500.00    |
| Carl     | -500.00    |
+----------+------------+

之后甚至可能按月分组(但这不是这个问题的一部分,我希望能够解决这个问题,如果我解决了这个问题。)

我尝试了各种各样的连接,但我最终得到了很多重复,而且我不确定如何同时进行SUM和分组。有谁知道怎么做?

4 个答案:

答案 0 :(得分:3)

试试这个

SELECT seller, SUM(amount) FROM InvoiceRow 
JOIN InvoiceHead 
ON InvoiceRow.InvoiceNr = InvoiceHead.InvoiceNr
GROUP BY InvoiceHead.seller;

或者如果你想在两个约会之间。试试这个

SELECT seller, SUM(amount) FROM InvoiceRow 
JOIN InvoiceHead 
ON InvoiceRow.InvoiceNr = InvoiceHead.InvoiceNr
WHERE InvoiceHead.Date >= '2016-01-01' AND InvoiceHead.Date < '2016-02-01'
GROUP BY InvoiceHead.seller;

答案 1 :(得分:3)

您只需要加入表格,根据需要按日期过滤结果,然后进行分组:

select
   H.Seller,
   sum(R.Amount) as Amount
from InvoiceHead as H
    left outer join InvoiceRow as R on R.InvoiceNr = H.InvoiceNr
where H. Date >= '2016-01-01' AND H.Date < '2016-02-01' 
group by H.Seller

答案 2 :(得分:1)

SELECT t.seller,sum(s.amount)
FROM invoiceRow s join InvoiceHead t
ON s.invoiceNr = t.invoiceNr 
group by t.seller

你应该总结一下。如果需要日期范围,可以在ON子句后添加where子句,并按如下方式过滤日期:

SELECT t.seller,sum(s.amount)
FROM invoiceRow s join InvoiceHead t
ON s.invoiceNr = t.invoiceNr 
WHERE t.date between '01-01-2016' and '31-01-2016' 
group by t.seller

答案 3 :(得分:1)

您可以尝试一次:

    SELECT ih.Seller,   
     (
        SELECT SUM(Amount) FROM invoicerow ir
        INNER JOIN invoicehead ih1
            ON (ir.InvoiceNr = ih1.InvoiceNr)
            WHERE ih1.Seller = ih.Seller
        ) AS Amount 
    FROM invoicehead ih 
    GROUP BY  ih.Seller