postgresql从连接中重复计算

时间:2013-02-27 16:27:01

标签: postgresql join

所以我有以下查询

SELECT SUM(s.price) as "totalSales", 
       sum(CASE 
             WHEN er.verified AND er.price = 1.010101 THEN s.price 
             WHEN er.verified AND er.price > 1.010101 THEN er.price ELSE 0 END) as "totalRet", 
       c.company as "client"
FROM "Esns" e 
  JOIN "EsnsSalesOrderItems" es on es."EsnId" = e."id" 
  JOIN "SalesOrderItems" s on es."SalesOrderItemId" = s.id
  JOIN "SalesOrders" so on so.id = s."SalesOrderId"
  JOIN "Clients" c on so."ClientId" = c.id                    
  LEFT OUTER JOIN  "EsnsRmas"  er on er."EsnId" = e.id
GROUP BY c.id

但是,如果es上有多个“EsnId”,它将多次计数,反之亦然。

我如何构建以便一切只计算一次?

1 个答案:

答案 0 :(得分:1)

SELECT
    SUM(s.price) as "totalSales", 
    sum(CASE 
        WHEN er.verified AND er.price = 1.010101 THEN s.price 
        WHEN er.verified AND er.price > 1.010101 THEN er.price ELSE 0 END) as "totalRet", 
    c.company as "client"
FROM "Esns" e 
    JOIN (
        select distinct "EsnId"
        from "EsnsSalesOrderItems"
    ) es on es."EsnId" = e."id" 
    JOIN "SalesOrderItems" s on es."SalesOrderItemId" = s.id
    JOIN "SalesOrders" so on so.id = s."SalesOrderId"
    JOIN "Clients" c on so."ClientId" = c.id                    
    LEFT OUTER JOIN  "EsnsRmas"  er on er."EsnId" = e.id
GROUP BY c.id