[英]SQL Query to Get Max Value Based on Different Max Value Given Multiple Records
我知道我可以用CTE或其他方法做到這一點,但我想知道這是否可以在一個選擇查詢中完成(沒有子選擇)。 我想找到po_nbr的最新crt_ts,然后獲取相關的id。
id列不保證是順序的,我簡化了這個問題。
create table temp
(
id int,
po_nbr int,
crt_ts datetime
)
insert into temp values (20, 100, '09/01/2009')
insert into temp values (3, 100, '09/03/2009')
insert into temp values (5, 100, '09/05/2009')
insert into temp values (6, 100, '09/07/2009')
insert into temp values (4, 200, '08/01/2009')
insert into temp values (29, 200, '08/03/2009')
insert into temp values (12, 200, '08/05/2009')
insert into temp values (18, 200, '08/07/2009')
id po_nbr
---------
6 100
18 200
SELECT
MAX(id) id,
po_nbr
FROM
temp
GROUP BY
po_nbr
要獲得相關日期,您可以這樣做(請注意,這意味着一個順序ID):
SELECT
temp.id,
temp.po_nbr,
temp.crt_ts
FROM
temp
INNER JOIN (
SELECT MAX(id) id FROM temp GROUP BY po_nbr
) latest ON latest.id = temp.id
沒有順序ID,它將是:
SELECT
MAX(temp.id) id,
temp.po_nbr,
temp.crt_ts
FROM
temp INNER JOIN (
SELECT MAX(crt_ts) crt_ts, po_nbr
FROM temp i
GROUP BY po_nbr
) latest ON latest.crt_ts = temp.crt_ts AND latest.po_nbr = temp.po_nbr
GROUP BY
temp.po_nbr,
temp.crt_ts
如果每個po_nbr
組保證沒有兩個相等的日期,則可以省略GROUP BY
。
crt_ts
和po_nbr
上的索引在最后一個查詢中有幫助,創建一個組合索引是最好的。
嘗試:
SELECT
id,po_nbr --crt_ts --can show the date if you want
FROM (SELECT
id,po_nbr,crt_ts
,ROW_NUMBER() OVER(partition BY po_nbr ORDER BY po_nbr,crt_ts DESC) AS RankValue
FROM temp
) dt
WHERE RankValue=1
SELECT
MAX(temp.id) AS id, det.po_nbr
FROM
temp
INNER JOIN (SELECT po_nbr, MAX(crt_ts) AS maxcrt_ts FROM temp GROUP BY po_nbr) AS det ON temp.po_nbr = det.po_nbr AND temp.crt_ts = maxcrt_ts
GROUP BY
det.po_nbr
select t.id, tm.po_nbr
from temp t
inner join (
select po_nbr, max(crt_ts) as max_ts
from temp
group by po_nbr
) tm on t.po_nbr = tm.po_nbr and t.crt_ts = max_ts
通過po_nbr從tempbarry group中選擇max(id),po_nbr
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.