2012-07-05 14 views
-3

選擇最大的項目,我創建的表像PGSQL表

CREATE TABLE dataset (
    identifier character varying(15) NOT NULL, 
    description character varying(3000) NOT NULL, 
    publisher character varying(45) NOT NOT NULL, 
    publication_date date, 
    modification_date date, 
    title character varying(600) NOT NULL, 
    release_date date 
) 

如何選擇最大的標識符 如。

10001/01 
10001/02 
10001/03 
10001/04 

選擇10001/04

+0

標識符例如100010/0001,100010/0002 .... – AntiGMO

+0

我需要得到最大的一個/。像100010/111,共111項 – AntiGMO

回答

1

爲什麼你需要一段文本(不同的(15))作爲標識?通常使用一個從序列中獲取下一個數字的數字。使用數據類型SERIAL,全部爲您處理,請參閱manual

您也可以使用MAX()來獲得最大的數字,但永遠不會嘗試將其用作「下一個數字」,因爲這不起作用。有可能是別人在同一個數量的工作......

0

您可以通過「大」是指上線4

得到了一個語法錯誤,NOT NOT NULL如果「最長」,那麼這樣的事情可以幫助你出:

select identifier from dataset order by length(identifier) desc limit 1; 

如果你想在一個文本比較 - 格式「最大」項目(即「富」>「欄」),然後使用MAX:

select max(identifier) from dataset; 

這也將有助於如果標識符是nu meric以字符串格式(警告......由於一些奇怪的區域設置...和'9'>'10',我曾經遇到'-1'>'0')。

您也可投標識爲int的飛行,如果它的數字:

select max(identifier::int) from dataset; 

考慮到額外的信息,這是一個願望斜線後比較數量,試試這個:

select identifier from dataset 
order by substring(identifier from '/([0-9]*)$')::int desc limit 1; 

要速度,你可以在子表達式添加一個索引:

create index dataset_by_substring on dataset 
(substring(identifier from '/([0-9]*)$')); 
+0

hi tobixen標識符包含/但我想得到最大的一個比較/後的數字。如10001/01 <10001/02選擇10001/02 – AntiGMO

+0

我會使用正則表達式...我會在幾分鐘內將它添加到我的答案中。 – tobixen

1

喜歡的東西這

select parts[1], max(parts[2]) 
from ( 
    select identifier, 
      regexp_split_to_array(identifier, '/')::int[] as parts 
    from dataset 
) t 
group by parts[1]; 
0
select max(
     substring(
       identifier, 
       position('/' in identifier) + 1, 
       length(identifier) - position('/' in identifier) 
       )::integer 
    ) 

我知道這是不是很漂亮。