0

所以我有以下查询

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”,则会多次计数er,反之亦然。

我如何构建以使所有内容都只计算一次?

4

1 回答 1

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
于 2013-02-27T17:40:13.477 回答