SQL聚合调用

时间:2013-04-15 10:06:08

标签: sql postgresql

我有两张表

1)客户

  id  |       name        
------+-------------------
    1 | xyz1
    2 | xyz2
    3 | xyz3
    4 | xyz4
    5 | xyz5

2)产品

  id  |       name  | customer | state      
------+-------------+----------+-------
    1 | product 1   |    1     |Shipped    
    2 | product 2   |    1     |Pending 
    3 | product 3   |    1     |Shipped 
    4 | product 4   |    1     |Pending 
    5 | product 5   |    2     |Shipped 

我想查询类似的内容:

SELECT name from customer, SELECT count(*) from products where state='SHIPPED', SELECT count(*) from product where state='PENDING' for all developers产生以下结果:

   name  | count_shipped | count_pending      
  -------+---------------+---------------
    xyz1 | 2             | 2
    xyz2 | 1             | 0
    xyz3 | 0             | 0
    xyz4 | 0             | 0
    xyz5 | 0             | 0

3 个答案:

答案 0 :(得分:2)

select c.name,
       sum(case when p.state = 'Pending' then 1 else 0 end) as count_pending,
       sum(case when p.state = 'Shipped' then 1 else 0 end) as count_shipped
from customer c 
   left join products p on p.customer = c.id
group by name;

答案 1 :(得分:0)

SELECT
    c.id , 
    c.name ,
    SUM(IF p.state = 'Shipped',1,0) AS count_shipped,
    SUM(IF p.state = 'Pending',1,0) AS count_pending
FROM Customer AS c
LEFT JOIN Products AS p ON p.customer = c.id
GROUP BY c.id

答案 2 :(得分:0)

您也可以使用COUNT ...

SELECT c.name
     , COUNT(CASE WHEN state = 'shipped' THEN 'foo' END) count_shipped 
     , COUNT(CASE WHEN state = 'pending' THEN 'foo' END) count_pending 
  FROM customer c 
  LEFT
  JOIN products p  
    ON p.customer = c.id 
 GROUP  
    BY c.id;