使用postgreSQL进行子查询计算

时间:2018-07-09 07:10:20

标签: sql postgresql subquery aggregate

我通过编写以下查询得出查询结果

   SELECT a.indent_date as "Invoice_Date", a.indent_no as "Invoice_No",
          d.product_description as "Product Description",
          e.name as "Product_Category",
          c.name as "Customer",
          a.amount as "Invoice_Amount",
     FROM indents a
     JOIN parties b on (a.supplier_id = b.id)
     JOIN parties c on (a.buyer_id = c.id)
     JOIN indent_items d on (a.id = d.indent_id)
     JOIN product_categories e on (a.product_category_id = e.id)
    WHERE c.name <> 'SOFEENE ENTERPRISES' 
      And b.name = 'SOFEENE ENTERPRISES' 
      And indent_date >= '2017-10-01 00:00:00' 
      And indent_date <= '2017-12-31 00:00:00'
 Order By indent_date ASC

该表格如下所示

Invoice_Date    Invoice_No  Product Category    Customer    Invoice_Amount 
    2/10/2017          1          Spandex       A                     1000  
    3/10/2017          2          Spandex       B                     2000  
    3/10/2017          2          Spandex       B                     1000  
    3/10/2017          2          Spandex       B                     2000  
    3/10/2017          2          Spandex       B                     1000  
    4/10/2017          3          Spandex       B                     2000  
    4/10/2017          3          Spandex       B                     1000  
    4/10/2017          3          Spandex       B                     2000  
    4/10/2017          3          Spandex       B                     1000  
    4/10/2017          3          Spandex       B                     2000

现在,我要从该表中进行另一个查询,并且我的终端表应该看起来像

Invoice_Date    Invoice_No  Product Category    Customer    Invoice_Amount
2/10/2017              1            Spandex           A              1000
3/10/2017              2            Spandex           B              6000
4/10/2017              3            Spandex           B              8000

实际上,我想按Invoice_no分组并添加发票金额。

我尝试了子查询,但是以某种方式无法正常工作。 我正在使用Postgres SQL。

1 个答案:

答案 0 :(得分:1)

您需要添加分组并汇总发票金额:

SELECT a.indent_date as "Invoice_Date", a.indent_no as "Invoice_No",
       d.product_description as "Product Description",
       e.name as "Product_Category",
       c.name as "Customer",
       sum(a.amount) as "Invoice_Amount" -- put a SUM() around that
       FROM indents a
JOIN parties b on (a.supplier_id = b.id)
JOIN parties c on (a.buyer_id = c.id)
JOIN indent_items d on (a.id = d.indent_id)
JOIN product_categories e on (a.product_category_id = e.id)
WHERE c.name <> 'SOFEENE ENTERPRISES' and b.name = 'SOFEENE ENTERPRISES' 
      and indent_date >= '2017-10-01 00:00:00' 
      and indent_date <= '2017-12-31 00:00:00'
GROUP BY 1,2,3,4,5 -- these qualify for columns in order from SELECT list
ORDER BY indent_date

如果您在SELECT中的列顺序发生了变化,分组也会发生变化,因此这可能是一个方便的快捷方式,但是当您四处乱走列显示时,请务必谨慎调整它。如果您希望以通常的方式使用它,只需:

GROUP BY a.indent_date, a.indent_no, d.product_description, e.name, c.name