首先:我不确定这个问题是否可以仅通过 sql 查询来解决,但无论如何这是我可以使用 atm 的唯一解决方案。 我不想使用另一种编程语言,也不想在我的数据库中创建新表。 如果这在纯 SQL 中是不可能的,那也是我可以使用的答案。 ;-)
所以这里是:
我有 3 个表,其中包含许多列,但我只需要每个表中的一两个:orders.orders_no、status.orders_no status.order_status、state.orders_no、state.order_state。
orders_no 编号为1-100; status.order_status为状态A,状态B; state.order_state 是德国、英国、法国、美国、印度等。
我需要的是一个类似于 group by 的表格,但另外总是显示状态 A、状态 B、每个状态和每个订单的状态数量,即使状态 A 或 B 的数量,对于一个给定的状态和顺序为空。
如果你能帮助我,那就太好了!谢谢!
示例:
对 orders_no 上的 3 个表进行完全外部联接的原始表
order.orders_no | status.order_status | state.order_state
1 | staus a | DE
1 | staus a | DE
1 | staus b | FR
1 | staus b | DE
2 | staus a | GB
2 | staus a | DE
2 | staus b | DE
2 | staus b | DE
2 | staus b | DE
2 | staus b | FR
3 | staus a | DE
查询结果:
order.orders_no | status.order_status | state.order_state| count
1 | staus a | DE | 2
1 | staus b | DE | 1
1 | staus b | FR | 1
1 | staus a | FR | 0
2 | staus a | GB | 1
2 | staus b | GB | 0
2 | staus a | DE | 1
2 | staus b | DE | 3
2 | staus a | FR | 0
2 | staus b | FR | 1
3 | staus a | DE | 1
3 | staus b | DE | 0
最佳答案
一些自连接就可以了:
SELECT x."order", x.status, x.state, count( t.state )
FROM (
SELECT DISTINCT "order", t1.status, t2.state
FROM table1 t1
JOIN table1 t2 USING ( "order" )
) x
LEFT JOIN table1 t
ON x."order" = t."order" AND x.status = t.status AND x.state = t.state
GROUP BY x."order", x.status, x.state
ORDER By 1,2,3
关于sql - 使用 postgreSQL 按表填充分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27987815/