2016-07-14 55 views
3

我有一個Postgresql數據庫,並且我無法正確地查詢我的查詢,儘管這看起來像是一個常見問題。從數據庫中的每個用戶獲取最後一個條目

我的表看起來像這樣:

CREATE TABLE orders (
    account_id INTEGER, 
    order_id  INTEGER, 
    ts   TIMESTAMP DEFAULT NOW() 
) 

每當有一個新的秩序,我用它來鏈接account_idorder_id

現在我的問題是,我想要獲得最後一個訂單的列表(通過查看ts)爲每個帳戶。

例如,如果我的數據是:

account_id order_id   ts 
     5   178  July 1 
     5   129  July 6 
     4   190  July 1 
     4   181  July 9 
     3   348  July 1 
     3   578  July 4 
     3   198  July 1 
     3   270  July 12 

然後我想查詢只返回最後一排爲每個帳戶:

account_id order_id   ts 
     5   129  July 6 
     4   181  July 9 
     3   270  July 12 

我試過GROUP BY account_id,並我可以使用它爲每個帳戶獲得MAX(ts),但是我無法獲得關聯的order_id。我也嘗試了子查詢,但我似乎無法做到。

謝謝!

+0

你必須有一些主鍵,所以使用'LIMIT 1'和'ORDER BY ID DESC'。它顛倒了順序並將其限制爲1(所以最高的ID是第一個結果,限制則只有這1個結果)。 –

+0

試試看這裏:http://stackoverflow.com/questions/331367/sql-statement-help-select-latest-order-for-each-customer –

+0

@Rajat我不想只是一排,我想要一排爲每個account_id。 – gattoo

回答

3
select distinct on (account_id) * 
from orders 
order by account_id, ts desc 

https://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT

SELECT DISTINCT ON(表達式[,...])保持各組的僅第一行給定表達式求值相等的行。 DISTINCT ON表達式使用與ORDER BY相同的規則進行解釋(請參見上文)。請注意,除非使用ORDER BY來確保所需的行首先出現,否則每個集合的「第一行」是不可預知的。

+0

優秀!很棒!謝謝! 我甚至會在之前使用DISTINCT,但不知道ON關鍵字。 – gattoo

+1

只是一個註釋:顯然'DISTINCT ON(表達式)'是Postgresql的東西。這不是標準的SQL。儘管如此,仍然是最好的答案,因爲我使用Postgresql。 – gattoo

2

row_number()的窗函數可以幫助:

select account_id, order_id, ts 
    from (select account_id, order_id, ts, 
       row_number() over(partition by account_id order by ts desc) as rn 
      from tbl) t 
where rn = 1 
相關問題