SQL查询处理三个表

时间:2012-07-05 11:57:34

标签: sql postgresql

我想使用php与postgres进行通信来编译数据以进行报告, 我有三张桌子

product_status

status_code | value
------------|------
    1       |  a
    2       |  b

product_child

code| ID | status_code
----|----|------------
 X  |  1 |   1
 X  |  2 |   1
 X  |  3 |   2
 Y  |  1 |   2
 Y  |  2 |   2
 Z  |  1 |   1

product_master

code|description(and some other columns not relevent)
 X  |    la
 Y  |    alb
 Z  |    lab

最后我想要一个像这样的表格,我会显示

    | total child | status a | status b
bla |    3        |  2       |   1
alb |    2        |  0       |   2
lab |    1        |  1       |   0

我试过了

SELECT s.value, count(s.value) 
FROM product_child p, product_status s 
WHERE
    p.product_status = s.status_code 
    and p.product_code = get_product_code('Sofa (1-seater) J805') 
group by 
    s.value

它让我们对特定代码进行分组,但我希望将其翻转并附加在不同的product_codes前面

1 个答案:

答案 0 :(得分:1)

你是说这个意思吗?

select  pm.description,
        count(pc.code) total,
        count(case when ps.value = 'A' then ps.value else null end) statusA,
        count(case when ps.value = 'B' then ps.value else null end) statusB
from    product_master pm join product_child pc on pm.code = pc.code
        join product_status ps on pm.status_code = ps.status_code
group by pm.description