SQL 查询处理三个表

标签 sql postgresql

我想编译数据用于报告目的,使用 php 与 postgres 通信, 我有三张 table

产品状态:

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 之前

最佳答案

你是这个意思吗?

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

关于SQL 查询处理三个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11343846/

相关文章:

php - 如何查找自定义字段等于 '1234' 的 phpBB 用户?

postgresql - 表数据更改时如何在前端触发 NOTIFICATION 事件

javascript - 如何为 inet 设置 sequelize postgres 模型类型?

javascript - 序列化 : How to query model by 1:n association, 但在单个查询中包含所有关联对象 (PostgreSQL)

sql - PostgreSQL - 按数组排序

sql - 我的存储过程缺少哪些访问权限

php - MySQL LEFT JOIN 表或 PHP 组合数组

mysql - Wordpress SQL 与类别添加

ruby-on-rails - PostgreSQL:如何解决 ts_vector 大小限制?

mysql - SQL ORDER BY 多列