2013-02-27 46 views
0

,所以我有以下查詢PostgreSQL的雙數加入

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
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 
+0

因此,它不工作,因爲它只會計數一個es,如果有多個。我需要發生的是它計算多個ES,但後來知道它不應該再次計數,因爲它以前已經計算過了。 – user1175817 2013-02-27 20:31:48