Postgres: Group by a LIKE expression?

时间:2015-08-14 22:59:24

标签: postgresql

I'm using Postgres 9.4. I have the following query:

select sum(items) as items, sum(cost) as cost, 
       presentation_code, processing_date as date 
  from vw_presentation_summary 
  where presentation_code LIKE '011%' OR presentation_code LIKE '012%' 
  GROUP BY date, presentation_code;

This gives me results like this:

 items |       cost       | presentation_code |    date
-------+------------------+-------------------+------------
  8243 |        273445.45 | 0212000AAAAACAC   | 2014-03-01
   366 |         10511.99 | 0212000AABBABAB   | 2013-05-01
   461 |          9232.04 | 0212000AABBADAD   | 2014-02-01

But is there any way I can group all the results for 011% together, and all the results for 012% together?

2 个答案:

答案 0 :(得分:1)

您可以按照postgres中的任何表达式进行分组,这里的问题是presentation_code需要是某种类型的聚合或以可以分组的方式截断。这是一个例子:

select sum(items) as items, sum(cost) as cost, 
       CASE WHEN presentation_code LIKE '011%' THEN '011'
            WHEN presentation_code LIKE '012%' THEN '012'
       END AS code,
       processing_date as date 
  from vw_presentation_summary 
  where presentation_code LIKE '011%' OR presentation_code LIKE '012%' 
  GROUP BY date, code;

答案 1 :(得分:0)

group by left(presentation_code, 2)