2017-10-28 98 views
0

我有一個這樣的桌子。總銷售額和按月購買相同記錄組?

id date  subtotal type 
1 |2017-12-12 | 50.00 | 1 
2 |2017-12-12 | 20.00 | 2 
3 |2017-11-12 | 30.00 | 2 
4 |2017-11-12 | 40.00 | 1 
5 |2017-10-12 | 70.00 | 1 
6 |2017-10-12 | 250.00| 2 

在這種情況下,類型列顯示銷售(1)和購買(2)。我想要做的是,按月按此訂單分組,並在本月獲得總銷售額和購買量。像這樣的東西。

id date  sale  buy 
1 |December | 50.00 | 20.00 
2 |November | 30.00 | 40.00 
3 |October | 70.00 | 250.00 

當我嘗試這樣的事情,

select to_char(date,'Mon') as Month, 
     extract(year from date) as Year, 
     case when type= 1 then sum("subtotal") END as sales, 
     case when type= 2 then sum("subtotal") END as buys 
    from table 
    group by 1,2,type 

結果並不像我所希望的。這幾個月將出現在不同的列。喜歡這個。

month year sales buys 
Oct |2017| 70.00 | 0 
Oct |2017| 0  | 250.00 

我該如何做到這一點?我只想每月總結記錄。

回答

1

你想有條件聚集:

select to_char(date,'Mon') as Month, 
     extract(year from date) as Year, 
     sum(case when type = 1 then subtotal else 0 end) as sales, 
     sum(case when type = 2 then subtotal else 0 end) as buys 
from table 
group by Month, Year; 

我經常發現它方便地在這種情況下使用date_trunc()

select date_trunc('month', date) as month_start, 
     sum(case when type = 1 then subtotal else 0 end) as sales, 
     sum(case when type = 2 then subtotal else 0 end) as buys 
from table 
group by month_start 
order by month_start; 
+0

第一個完全像我想要的。謝謝。我沒有得到第二個想法。它只給出一個值。 – mext

0

在您的查詢中,您也按年份分組,這就是爲什麼它將所有內容合計在同一行中。 這應該給你想要的東西:

select to_char(date,'Mon') as Month, 
     extract(year from date) as Year, 
     case when type= 1 then sum("subtotal") END as sales, 
     case when type= 2 then sum("subtotal") END as buys 
    from table 
    group by 1 
+0

它說列「table.date」必須出現在GROUP BY子句中或用於聚合函數中。 – mext

+0

我的不好,你可以在group by子句中包含年份列,你不需要這個類型。 –

0

你可以試試這個

Select a.Month,a.Year,sum(a.sales) sales,sum(a.buys) buys 
from ( 
    select convert(char(3),date, 0) as Month, 
     year(date) as Year, 
     isnull(case when type= 1 then sum(subtotal) END,0) as sales, 
     isnull(case when type= 2 then sum(subtotal) END,0) as buys  
    from _table  
    group by convert(char(3),date, 0),year(date),type 
) a 
group by a.Month,a.Year 
+0

我在這個上得到語法錯誤。另外我沒有一個a.sales和a.buys在開始。我只有轉換爲銷售額並從類型值購買的小計。 – mext

+0

Postgres中沒有'convert()'。 –