2016-11-22 120 views
-3

請幫我查詢 下面是桌子和要求的詳細信息PostgreSQL的查詢

enter image description here

+2

請澄清你是否想要MySQL或PostgreSQL的解決方案。您已經用兩種產品標記了問題,但每種解決方案可能有所不同。你的問題標題說'postgresql查詢',但爲什麼要標記MySQL的問題? –

+2

發佈你的代碼,而不是你的代碼的圖片。 – WillardSolutions

+0

https://stackoverflow.com/help/how-to-ask –

回答

1

您應該使用窗口功能

select alph_letter, alph_group, min(alph_date) OVER (PARTITION BY alph_group) AS min_date from alphabets; 
+0

感謝您的快速解決方案 –

1

你可以使用的min開窗變種:

SELECT letter, group, MIN(date) OVER (PARTITION BY group) 
FROM alphabets 
1

這是另一種方式:)。我使用SQL Server,但語法應該是這個問題類似:

示例數據:

IF OBJECT_ID('tempdb..#Alphabets') IS NOT NULL 
    DROP TABLE #Alphabets; 

CREATE TABLE #Alphabets(Letter VARCHAR(1) 
        , Groups VARCHAR(3) 
        , Dates DATE); 

INSERT INTO #Alphabets 
VALUES 
     ('A' 
    , 'abc' 
    , '20161026'), 
     ('B' 
    , 'abc' 
    , '20161027'), 
     ('C' 
    , 'abc' 
    , '20161028'), 
     ('D' 
    , 'def' 
    , '20161101'), 
     ('E' 
    , 'def' 
    , '20161030'); 

QUERY:

SELECT B.Letter 
    , B.Groups 
    , MinDates 
FROM 
     (SELECT MIN(Dates) AS MinDates 
      , Groups 
     FROM #Alphabets 
     GROUP BY Groups) AS A 
     INNER JOIN #Alphabets AS B ON A.Groups = B.Groups; 

結果:

enter image description here