SQL Server咨询中的最大日期

时间:2017-12-11 19:03:48

标签: sql sql-server tsql transactions

我需要获取ItemKey的最大日期行。

我需要整行。

我有这张桌子:

num | ItemKey | Serial | Qty | ItemName | Tdate
----+---------+--------+-----+----------+-------------------------
1   | 111     | 5      | 10  | AAA      | 2010-03-25 00:00:00.000 
2   | 111     | 0      | 12  | AAA      | 2010-03-26 00:00:00.000 
3   | 222     | 6      | 13  | BBB      | 2010-03-25 00:00:00.000 
4   | 222     | 2      | 11  | BBB      | 2010-03-28 00:00:00.000 
5   | 333     | 3      | 15  | CCC      | 2010-03-25 00:00:00.000 
6   | 333     | 4      | 16  | CCC      | 2010-03-26 00:00:00.000 
7   | 333     | 0      | 17  | CCC      | 2010-03-27 00:00:00.000 

我需要得到这个:

num | ItemKey | Serial | Qty | ItemName | Tdate
----+---------+--------+-----+----------+--------------------------
2   | 111     | 0      | 12  | AAA      | 2010-03-26 00:00:00.000 
4   | 222     | 2      | 11  | BBB      | 2010-03-28 00:00:00.000
7   | 333     | 0      | 17  | CCC      | 2010-03-27 00:00:00.000

我尝试了这个SQL语句:

select * 
from MyTBL 
where Tdate = (select MAX(Tdate) from MyTBL)

但不幸的是它不起作用

由于

4 个答案:

答案 0 :(得分:3)

您可以使用ROW_NUMBER来实现此目标

SELECT * FROM (
select *,
       ROW_NUMBER() OVER (PARTITION BY ItemKey  ORDER BY Tdate DESC) as rn from MyTBL) AS T1
WHERE rn = 1

或以其他方式(使用公用表表达式)

WITH CTE_1 AS (
    select *,ROW_NUMBER() OVER (PARTITION BY ItemKey  ORDER BY Tdate DESC) as rn from MyTBL)
SELECT * FROM CTE_1 WHERE rn = 1

答案 1 :(得分:0)

SQL HERE

您可以使用:

select t1.* from table_name t1
join (select ItemKey, max(Tdate) Tdate from table_name group by ItemKey) as t2 
      on t1.ItemKey=t2.ItemKey and t1.Tdate=t2.Tdate
order by t1.ItemKey

答案 2 :(得分:0)

试试这个;

   select * from MyTBL M1 inner join
    (select ItemName,max(Tdate) as Tdate from MyTBL group by ItemName) M2
    ON M1.ItemName = M2.ItemName and  M1.Tdate = M2.Tdate

答案 3 :(得分:0)

试试这个

WITH t AS ( SELECT *, RANK() OVER (PARTITION BY ItemName ORDER BY TDate DESC ) as myRank from MyTBL) SELECT [num], [ItemKey], [Serial], [Qty], [ItemName], [TDate] FROM t WHERE t.myRank = 1

SQL fiddle