简体   繁体   English

SQL查询处理三个表

[英]SQL query handling three tables

I want to compile the data for reporting purpose, using php communicating with postgres, I have three tables 我想编译数据用于报告目的,使用与postgres进行php通讯,我有三个表

product_status : product_status

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

product_child : 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 : product_master

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

In the end I want basically a table like this which i'll display 最后,我基本上想要一个这样的表,我将显示它

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

I have tried 我努力了

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

it gives we grouping for particular code but I want this flipped and appended in front of distinct product_codes 它使我们可以对特定代码进行分组,但我希望将其翻转并附加在不同的product_codes前面

do you mean like this? 你是这个意思吗

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM