SQL Query用于获取具有列的最大值的表的行详细信息

时间:2011-01-03 09:52:41

标签: sql tsql

我有两张桌子。

表1

Num 
1
2
3

表2

Num   Date    Amount
1     12/31     30
1     12/30     31
1     12/29     20
2     12/31     100
2     12/30     90
3     12/31     12
4     11/1       1

现在我的结果应该

   Num   Date    Amount
    1    12/31     30
    2    12/31     100 
    3    12/31     12

(对于表1中的'Num'值,加入table2,其中日期是最新的)

我正在尝试编写一个tsql查询来实现这一目标。

感谢任何帮助。感谢

4 个答案:

答案 0 :(得分:2)

如果您想要每个table1 num的最新日期:

with maxdates as (
    select  T1.num, max(T2.date) as date
      from  table2 T2
      join  table1 T1
        on  T2.num = t1.num
    group by T1.num
)
select  t2.num, t2.date, t2.amount
  from  table2 T2
  join  maxdates M
    on  T2.num = M.num
    and T2.date = M.date

或者如果您想要表格中所有匹配记录的最新日期:

with maxdate as (
    select  max(T2.date) as date
      from  table2 T2
      join  table1 T1
        on  T2.num = t1.num
)
select  t2.num, t2.date, t2.amount
  from  table2 T2
  join  table1 T1
    on  T2.num = T1.num
  join  maxdate M
    on  T2.date = M.date

答案 1 :(得分:2)

尝试此查询:

SELECT b.*
  FROM  Table1 a INNER JOIN
                (
        SELECT a.*, 
               ROW_NUMBER() OVER(PARTITION BY a.Num ORDER BY Date DESC) rnk
          FROM Table2  a
        ) b
        ON a.Num = b.Num
        AND rnk = 1

答案 2 :(得分:0)

试试这个

select t2.* from table2 as t2 inner join table1 as t1 on t2.num=t2.num
inner join
(
Select t2.num,max(t2.amount) as amount from table2 
group by  t2.num
) as t3 on t2.amount=t3.amount

答案 3 :(得分:0)

DECLARE @t1 TABLE(num INT)
DECLARE @t2 TABLE(num INT, [date] NVARCHAR(5), amount INT)

INSERT INTO @t1 (num) VALUES (1),(2),(3)

INSERT INTO @t2 (num,[date],amount) VALUES (1,'12/31',30)
INSERT INTO @t2 (num,[date],amount) VALUES (1,'12/30',31)
INSERT INTO @t2 (num,[date],amount) VALUES (1,'12/29',20)
INSERT INTO @t2 (num,[date],amount) VALUES (2,'12/31',100)
INSERT INTO @t2 (num,[date],amount) VALUES (2,'12/30',90)
INSERT INTO @t2 (num,[date],amount) VALUES (3,'12/31',12)
INSERT INTO @t2 (num,[date],amount) VALUES (4,'11/01',1)

SELECT t2.num,t2.[date],amount 
FROM @t1 t1 JOIN @t2 t2 ON t1.num = t2.num
WHERE t2.[date] in (
                        SELECT MAX(t3.[date]) 
                        FROM @t2 t3 
                        WHERE t3.num = t2.num
                    )
ORDER BY t2.num