2017-10-28 3 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 

この場合、タイプ列にはsales(1)とbuy(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 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

最初のものは私が欲しいのとまったく同じように動作します。ありがとうございました。私は2番目の考えを得ることはありません。それはただ一つの価値を与えます。 – mext

0

あなたのクエリでは、年ごとにグループ化しています。そのため、すべてが同じ行に集計されています。 これが何をしたいあなたを与える必要があります:私は、多くの場合、それが便利なこの状況でdate_trunc()を使用するために見つける

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; 

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

私の悪い、年の列だけでなく、グループ句で含めることができます、あなたはちょうど型が必要ありません。 –

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()'はありません。 –

関連する問題