2013-03-26 54 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