使用postgreSQL按表填充其他值

时间:2015-01-16 15:55:00

标签: sql postgresql

第一个:我不确定这个问题只能用sql-query解决,但无论如何这是我可以使用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是德国,英国,法国,美国,印度等。

我需要的是一个类似于分组的表,但另外总是显示状态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

1 个答案:

答案 0 :(得分:1)

一些自我加入可以解决这个问题:

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

演示:http://sqlfiddle.com/#!15/1dd67/21