按月计算同一记录组的总销售额和购买量?

时间:2017-10-28 09:42:47

标签: sql postgresql

我有一张像这样的桌子。

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

在这种情况下,type列显示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

我怎样才能做到这一点?我只想每月记录一次。

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

在您的查询中,您也按年份分组,这就是为什么它在同一行中的所有内容。 这应该给你你想要的东西:

waitpid(pid, &status, 0);

答案 2 :(得分: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