2012-10-12 60 views
0

可能重複:
SQL how to find rows which have highest value of specific column多列的最高值選擇行

這裏是我的表架構

--transaction_details-- 
transaction_id primary_key auto inc 
entity_name 
entity_transaction 

現在,一個實體可以有多個交易。我想查詢每個實體的最後一筆交易,這與查找特定列的this post不同。這可以通過選擇具有每個實體的最後/最大transaction_id的行來完成。但是我無法寫這個查詢。我嘗試使用組entity_name,但它選擇任何隨機行。

+0

可能重複:http://stackoverflow.com/q/3337469/1220971 – Bridge

+1

Naah,給出特定行的結果,我希望每個實體都有最高的id行。 – Sourabh

+1

@Sourabh:所以你會做同樣的事情,除了你的內部查詢將會「GROUP BY entity_name」。 – Jon

回答

0

你可以做這樣的事情,如果entity_transaction始終是相同的ENTITY_NAME相同:

select max(transaction_id), entity_name, entity_transaction 
from transaction_details 
group by entity_name, entity_transaction 

如果你可以有不同的值entity_transaction爲同一entity_name,使用此查詢:

select g.transaction_id, g.entity_name, d.entity_transaction 
from 
(
    select max(transaction_id) transaction_id, entity_name 
    from transaction_details 
    group by entity_name 
) g 
inner join transaction_details d 
    on g.entity_name = d.entity_name and g.transaction_id = d.transaction_id 
+0

不,它不一樣,如果它是相同的,爲什麼我需要一個特定的。 – Sourabh

+0

@Sourabh:顯然是因爲transaction_id。無論如何,我添加了另一個版本,請看看,並刪除downvote。 –

0

試試這個:

select * 
from <table> t 
join 
    (select entity_name,max(transaction_id) as transaction_id 
     from <table> 
     group by entity_name)a 
on a.entity_name=t.entity_name 
and a.transaction_id=t.transaction_id