postgresql子查询在更大的上下文中计数

时间:2013-02-26 16:18:45

标签: postgresql subquery

我有以下查询:

 SELECT sum(p.price) as "totalPurchase", sum(s.price) as "totalSale", sum(er.price) as          
 "totalRet", v.name as "vendor"
 FROM "Esns" e
 JOIN "EsnsPurchaseOrderItems" ep on ep."EsnId" = e.id
 JOIN "PurchaseOrderItems" p on ep."PurchaseOrderItemId"= p.id
 JOIN "PurchaseOrders" po on p."PurchaseOrderId" = po.id
 JOIN "Vendors" v on po."VendorId" = v.id
 LEFT OUTER JOIN "EsnsSalesOrderItems" es on es."EsnId" = e.id
 LEFT OUTER JOIN "SalesOrderItems" s on es."SalesOrderItemId" = s.id
 LEFT OUTER JOIN "EsnsRmas" er on er."EsnId" = e.id
 GROUP BY v.id

但是,我还要计算上面连接组织的所有e.id以及字段e。“inStock”= true。

1 个答案:

答案 0 :(得分:1)

SELECT  sum(p.price) as "totalPurchase", 
        sum(s.price) as "totalSale", 
        sum(er.price) as "totalRet", 
        v.name as "vendor",
        sum(CASE WHEN e."inStock" = true THEN 1 ELSE 0 END) as "totalInStock"
FROM    .....
GROUP   BY ....

OR

COUNT(CASE WHEN e."inStock" = true THEN 1 END) as "totalInStock"