2017-05-05 70 views
0

表的最後日期:SQL:加入表

MSUB - > ID,收到

msublist - > ID,sub_id,ITEM_ID,數量

我敢嘗試。

select a.sub_id 
, a.item_id 
, a.qty 
, b.id 
, b.receive_date 
from msublist a 
join (select x.id 
, x.receive_date 
from msub x 
where x.receive_date = (select max(x1.receive_date) 
         from msub x1 
         where x1.id = x.id)) b 
on (a.sub_id = b.id) 
order by a.item_id,b.receive_date desc 

it'not幹活想成爲ITEM_ID

+0

看起來像x.id沒有在你的第二個子查詢中定義最大日期。你得到了什麼確切的錯誤? – gaganshera

+0

您正在使用哪些DBMS? Postgres的?甲骨文? –

+0

http://stackoverflow.com/questions/tagged/greatest-n-per-group+sql –

回答

0

請嘗試以下...

SELECT msublist.sub_id AS msub_id, 
     msublist.item_id AS item_id, 
     msublist.qty AS qty, 
     msublist.id AS msublist_id, 
     mostRecentDate AS receive_date 
FROM msub 
JOIN msublist ON msub.id = msublist.sub_id 
JOIN (SELECT item_id, 
       MAX(receive_date) AS mostRecentDate 
     FROM msub 
     JOIN msublist ON msub.id = msublist.sub_id 
     GROUP BY item_id 
    ) AS mostRecentDateFinder ON msublist.item_id = mostRecentDateFinder.item_id 
           AND msub.receive_date = mostRecentDateFinder.mostRecentDate 
ORDER BY item_id; 

此語句開始與執行,並通過item_idINNER JOIN之間msubmsublist,然後組結果的子查詢。然後對於每個組(即,對於每個item_id值),它找到對應的值的最大值。

結果列表然後有它和從以這樣的方式對他們的共同的值接合msubmsublist產生的數據集之間執行INNER JOIN只有來自具有的item_id匹配組合msub/msublist數據集的那些行和mostRecentDate被保留。

然後將得到的數據集按值item_id排序。

最後,返回所需的字段。

如果您有任何問題或意見,請隨時發佈相應評論。

+0

類型2.it'ok。謝謝 –

+0

答案修改並添加了解釋。不客氣 - 我很樂意提供幫助。請注意,如果答案確實回答了您的問題,並且它是最合適的答案,您可以通過單擊答案頂部旁邊的勾號來接受答案。這給答案者15分的小獎勵,並從StackOverflow的未答覆問題列表中刪除您的問題。 – toonice

0

顯示lastdate試試這個: -

select a.sub_id 
, a.item_id 
, a.qty 
, b.id 
, b.receive_date 
from msublist a 
inner join 
(
Select a.sub_id,b.id,a.item_id, max(b.receive_dt) as receive_date 
from 
msublist a 
inner join 
msub b 
on a.sub_id=b.id 
group by a.sub_id,b.id,a.item_id 
) b 
on a.sub_id=b.sub_id and a.item_id=b.item_id 

讓我知道如果您有任何疑問

+0

我想顯示每個項目的最後一次提款。 –

0

試試這個


select a.sub_id 
     , a.item_id 
     , a.qty 
     , b.id 
     , b.receive_date 
    from msublist a 
    join (select x.id 
     , x.receive_date 
     from msub x 
     where x.receive_date = (select max(x1.receive_date) 
           from msub x1 
           )) b 
    on a.sub_id = b.id 
    order by a.item_id,b.receive_date desc 

這是你的業務嗎?

+0

它只顯示最近繪製的項目。但我想顯示每個項目的最後一次撤消。 –

+0

如果可能的話,你可以用任何樣本數據清楚一點嗎? – Sowndarya