我需要获取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)
但不幸的是它不起作用
由于
答案 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)
您可以使用:
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