表定义
ColumnName Comments
CustomerID INT
SequenceNo INT
Comments VARCHAR(MAX)
CUSTOMER TABLE
CustomerID SequenceNo Comments
1 1 ABC D
1 2 CDE
1 3 ABC
1 4 ABC D
1 5 CDE
1 6 abc
2 7 ABC DEF
2 8
2 9 ABC DEF
2 10 DEF
2 11 XYZ 123
2 12 ABC
3 13 PQ RST
输出
CustomerID SequenceNo Comments
1 3 ABC
1 4 ABC D
1 5 CDE
1 6 abc
2 8
2 9 ABC DEF
2 10 DEF
2 11 XYZ 123
2 12 ABC
3 13 PQ RST
应过滤记录 1.仅显示所有客户的客户表中的唯一注释, 2.如果注释相同,则显示具有最大SequenceNo
的行答案 0 :(得分:1)
这假设您使用区分大小写的排序规则
SELECT CustomerID,
MAX(SequenceNo) AS SequenceNo,
Comments
FROM yourTable
GROUP BY CustomerID,Comments
ORDER BY CustomerID,MAX(SequenceNo)
如果您没有使用区分大小写的排序规则,请尝试以下操作:
SELECT CustomerID,
MAX(SequenceNo) AS SequenceNo,
Comments COLLATE SQL_Latin1_General_CP1_CS_AS
FROM yourTable
GROUP BY CustomerID,Comments COLLATE SQL_Latin1_General_CP1_CS_AS
ORDER BY CustomerID,MAX(SequenceNo)
答案 1 :(得分:0)
您可以使用窗口函数:
select c.*
from (select c.*,
row_number() over (partition by CustomerId, Comments
order by SequenceNo desc) as seqnum
from comments c
) c
where seqnum = 1;