SQL查询根据给定多个记录的不同最大值获取最大值

时间:2009-09-17 13:44:17

标签: sql sql-server-2005 tsql

我知道我可以用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

5 个答案:

答案 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_tspo_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