2016-08-03 42 views
0

我可以獲取各種數據多組由總

  • 的上衣

    • 女孩5
    • 男孩10
    • 女孩5名
    • 男生15

現在我想在查詢輸出增加一個額外的總計行。像

    • 女孩10
    • 男孩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

和表結構 –

回答

0

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

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

您可以閱讀documentationGROUPING SETS