2013-03-26 80 views
0

我需要列出在不同池中有多少辆车。Postgresql:按模式汇总结果

这里是我所得到的:

select count(*), pool from cars group by 2 order by 1 desc; 

count | pool 
-------+-------- 
    71 | A-12-A 
    69 | B-45-A 
    19 | A-45-B 
    18 | A-69-A 
    15 | B-12-B 
    13 | A-67-B 
(6 rows) 

但我真的不关心AVOUT的中间值。我只在第一个和最后一个字母(我们使用的汽车分类和内部价值)中进行讨论。

如果它甚至有可能,我怎么能得到这样的:

count | pool 
-------+-------- 
    89 | A-%-A 
    69 | B-%-A 
    32 | A-%-B 
    15 | B-%-B 
(6 rows) 

回答

1

事情是这样的:

select count(*) as cnt, 
     regexp_replace(pool, '-[0-9]{2}-', '-%-', 'gi') as clean_pool 
from cars 
group by clean_pool 
order by 1 desc; 

SQLFiddle:http://sqlfiddle.com/#!12/ac449/2

这假设中间部分总是包含两个数字。如果不是这种情况,您需要调整正则表达式来应对。

+0

非常感谢,这正是我一直在寻找的。 – abitmol 2013-03-26 16:20:34