2014-11-05 27 views
1

我有一個Postgres 9.1數據庫三代用表 - 客戶,發票和Line_Items末發票使用的是Postgres

我想創造出一個特別項目,以任何客戶的客戶和最後發票日期的客戶名單(具體所有以'L3'開頭的line_items.code的發票)。

首先,我想拉一個事務爲每個客戶(最後發票與「L3" 代碼)(盤算一旦創建這個列表,我可以加入客戶的名字)。

表是什麼像這樣:

客戶

cust_number last_name first_name 
=========== ======== ==================== 
1    Smith  John 
2    Jones  Paul 
3    Jackson Mary 
4    Brown  Phil 

交易

trans_number date   cust_number 
=========== ===========  ==================== 
1001   2014-01-01  1 
1002   2014-02-01  4 
1003   2014-03-02  2 
1004   2014-03-06  3 

個Line_Items

trans_number date   item_code 
=========== ===========  ==================== 
1001   2014-01-01  L3000 
1001   2014-01-01  M2420 
1001   2014-01-01  L3500 
1002   2014-02-01  M2420 
1003   2014-03-02  M2420 
1004   2014-03-06  L3000 

到目前爲止,我有:

Select transactions.cust_number, transactions.trans_number 
from transactions 
where transactions.trans_number in 
    (SELECT Line_Items.trans_number 
     FROM Line_Items 
     WHERE Line_Items.item_code ilike 'L3%' 
     ORDER BY line_items.date DESC 
    ) 
order by transactions.pt_number 

這拉爲每個客戶與發票上的「L3」代碼的所有發票,但我無法弄清楚如何做到有最後一張發票。

回答

0

你可以使用MIN或MAX:

SELECT Line_Items.trans_number, Max(line_items.date) As [last] 
From Line_Items 
Group By Line_Items.trans_number 
3

使用DISTINCT ON

SELECT DISTINCT ON (t.cust_number) 
     t.cust_number, t.trans_number 
FROM line_items l 
JOIN transactions t USING (trans_number) 
WHERE l.item_code ILIKE 'L3%' 
ORDER BY t.cust_number, l.date DESC; 

這將返回每cust_number最多一行 - 一個與最新trans_number。您可以自由添加更多列到SELECT列表中。

詳細說明:

+0

這工作得非常好。我沒有意識到SELECT DISTINCT和SELECT DISTINCT ON()之間的區別。我感謝您的幫助。謝謝。 – kipsoft 2014-11-05 21:53:08