postgresql中的Total by Multiple group

时间:2016-08-03 11:34:37

标签: sql postgresql postgresql-9.4

我可以获取某种数据

  • 上衣

    • girl 5
    • boy 10
    • girl 5
    • 男孩15

现在我想在查询输出中添加一个额外的Total行。像

    • girl 10
    • boy 25

这是我的查询

    SELECT id, cloth_type, gender, qty, from
(SELECT 
    g.id as id,cloth.type as cloth_type, g.gender as gender, g.qty as qty
    0 AS sortorder -- added a sortorder column
       from
            cloth_master cloth
            inner join
            gender_master g on cloth.gender_id = g.id
            group by cloth.type, g.gender g.id
    UNION ALL
        SELECT
            g.id as id,cloth.type as cloth_type, g.gender as gender, g.qty as qty
            1 AS sortorder -- added a sortorder column
       from
            cloth_master cloth
            inner join
            gender_master g on cloth.gender_id = g.id
            group by cloth.type, g.gender g.id
) AS unionquery
) ORDER BY sortorderenter

我尝试UNION ALL但没有得到确切的解决方案,任何人都可以指导我吗?

1 个答案:

答案 0 :(得分:1)

在Postgres中,您可以使用分组集;

select coalesce(col1, 'Total'), col2, count(*)
from t
group by grouping sets ((col1, col2), (col1));

您可以在documentation中了解GROUPING SETS