我有一个像:
这样的数据集 type seqID text
A 1 Text1a
A 2 Text2a
A 3 Text3a
B 1 Text1b
B 2 Text2b
如何按类型按类型排序最高的seqID?所以在上面的例子中,我希望返回包含A,3,Text3a和B,2,Text2b的行。
答案 0 :(得分:1)
SELECT *
FROM tmp t1
WHERE NOT EXISTS
(SELECT 1 FROM tmp t2 WHERE t1.type = t2.type AND t2.seqID > t1.seqID)
它不应该存在具有相同类型和更高seqID的任何其他行。
答案 1 :(得分:0)
SELECT t.* FROM
(
SELECT type, MAX(seqID) as maxId
FROM Table
GROUP BY type
) m
INNER JOIN Table t ON m.maxId = t.seqId
使用CTE
;WITH maxIds(maxId)
AS
(
SELECT type, MAX(seqID) as maxId
FROM Table
GROUP BY type
)
SELECT t.* FROM
Table t
INNER JOIN maxIds m ON m.maxId = t.seqID
答案 2 :(得分:0)
您需要一个ID,但由于“Text”在此示例中似乎是唯一的
CREATE TABLE #TMP
(type VARCHAR(3), seqID INT, [text] varchar(256))
insert #TMP values ('A' , 1 , 'Text1a')
insert #TMP values ('A' , 2 , 'Text2a')
insert #TMP values ('A' , 3 , 'Text3a')
insert #TMP values ('B' , 1 , 'Text1b')
insert #TMP values ('B' , 2 , 'Text2b')
SELECT * FROM #TMP T
where [text] IN
(SELECT TOP 1 [text] FROM #TMP t2 WHERE t.type = t2.type ORDER BY t2.seqID DESC)
答案 3 :(得分:0)
SELECT tbl.*
FROM
( SELECT type, MAX(seqID)
FROM tbl
GROUP BY type) maxes
WHERE
tbl.type= maxes.type AND
tbl.seqID= maxes.seqID
答案 4 :(得分:0)
如果您使用的是SQL Server 2005+,则可以使用ranking function(更具体地说,ROW_NUMBER()
):
SELECT
type,
seqID,
text
FROM (
SELECT
*,
rnk = ROW_NUMBER() OVER (PARTITION BY type ORDER BY seqID DESC)
FROM atable
) s
WHERE rnk = 1
答案 5 :(得分:0)
create table #tlb1(
[type] VARCHAR(3), seqID INT, [text] varchar(max)
)
declare @type varchar(3), @text varchar(max);
declare @seqID int;
declare seq_cursor cursor for
select [type], max(seqID) from tbl group by [type]
open seq_cursor
fetch next from seq_cursor into @type,@seqID
while(@@fetch_status=0)
begin
set @text= (select [text] from tbl where [type]=@type and seqID=@seqid);
insert into #tlb1 values (@type, @seqID,@text);
fetch next from seq_cursor into @type,@seqID
end
select * from #tlb1
close seq_cursor
deallocate seq_cursor
truncate table #tlb1
答案 6 :(得分:0)
尝试:
SELECT type, max(seqID),text
FROM 'db'
GROUP BY type
就这么简单。
答案 7 :(得分:-1)
EDITED解决方案。考虑这是一个伪代码(因为我不熟悉SQL服务器语法):
SELECT a.type, a.seqID, a.text FROM table a
JOIN
(SELECT type, max(seqID) seqID FROM table GROUP BY type) b
ON a.seqID = b.seqID AND a.type=b.type