我知道我可以用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
答案 0 :(得分:4)
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
如果确保每个GROUP BY
组没有两个相同的日期,则可以省略po_nbr
。
crt_ts
和po_nbr
上的索引有助于上一次查询,创建一个综合索引最好。
答案 1 :(得分:2)
尝试:
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
答案 2 :(得分: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
答案 3 :(得分:1)
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
答案 4 :(得分:0)
选择max(id),po_nbr 来自临时 分组由po_nbr