显示所有可能尺寸的CUBE PostgreSQL结果

时间:2019-01-03 12:47:03

标签: postgresql cube

我使用以下查询来获取数据透视表的多维数据集结果:

SELECT
    client,
    shop,
    SUM (sales)
FROM
    sales
GROUP BY
    CUBE (client, shop)
ORDER BY
    client,
    shop;

并获得输出:

client     shop       sales
null       null        1000
null       Shop A       400
null       Shop B       600
Client A   null         800
Client A   Shop A       200
Client A   Shop B       600
Client B   null         200
Client B   Shop A       200

请注意,客户B仅向商店A销售。

但是我需要一个输出(最后一行添加),其中输出显示维度(客户,商店)中所有可能的交点。如何更改我的查询?

client     shop       sales
null       null        1000
null       Shop A       400
null       Shop B       600
Client A   null         800
Client A   Shop A       200
Client A   Shop B       600
Client B   null         200
Client B   Shop A       200
Client B   Shop B      null

1 个答案:

答案 0 :(得分:2)

您需要查询与表左连接的clientshop的笛卡尔积:

select 
    client, 
    shop, 
    sum(sales)
from (
    select distinct client 
    from sales
    ) c
cross join (
    select distinct shop 
    from sales
    ) s
left join 
    sales t using (client, shop)
group by 
    cube(client, shop)
order by 
    client, shop;

  client  |  shop  | sum  
----------+--------+------
 Client A | Shop A |  200
 Client A | Shop B |  600
 Client A |        |  800
 Client B | Shop A |  200
 Client B | Shop B |     
 Client B |        |  200
          | Shop A |  400
          | Shop B |  600
          |        | 1000
(9 rows)