[英]How to select unique values looking at only one column in SQL Server?
I use the following query (in SQL Server 2008) to fetch the last 20 records from a table. 我使用以下查询(在SQL Server 2008中)从表中获取最后20条记录。
The query works as intended, my only problem is that this is a log table where a certain itemID
can appear several times. 该查询按预期工作,我唯一的问题是这是一个日志表,其中某个itemID
可以出现几次。 Is there a way that I can only select unique itemIDs here? 有没有办法我只能在这里选择唯一的itemID?
I tried using DISTINCT but this doesn't work here as not the whole rows are duplicates, just the itemID can appear multiple times (and then the time stamps or other data differ). 我尝试使用DISTINCT,但这在这里不起作用,因为不是整个行都是重复的,只是itemID可以出现多次(然后时间戳或其他数据不同)。
My SQL: 我的SQL:
ALTER PROCEDURE [dbo].[RC_FetchUpdates]
@departmentID int
AS
BEGIN
SET NOCOUNT ON;
SELECT TOP 20 A.itemID,
A.lastUpdate,
CONVERT(VARCHAR(11), A.modTime, 106) AS modTime,
A.modBy,
B.itemName,
B.linkRef
FROM RC_LogLinks A
LEFT JOIN RC_Links B
ON B.itemID = A.itemID
WHERE B.departmentID = @departmentID
AND A.lastUpdate <> 'Deleted'
ORDER BY A.modTime desc, B.itemName
FOR XML PATH('updates'), ELEMENTS, TYPE, ROOT('ranks')
END
It will be something like this: 将会是这样的:
WITH rankedLogLinks AS (
SELECT ROW_NUMBER() OVER (PARTITION BY A.itemID ORDER BY A.modTime DESC) AS rownum, A.itemID, A.lastUpdate, A.modTime, A.modBy
FROM RC_LogLinks A
WHERE A.lastUpdate <> 'Deleted'
)
SELECT r.itemID, r.lastUpdate, CONVERT(VARCHAR(11), r.modTime, 106) AS modTime, r.modBy, B.itemName, B.linkRef
FROM rankedLogLinks r
LEFT JOIN RC_Links B
ON B.itemID = r.itemID
WHERE B.departmentID = @departmentID
AND r.rownum = 1
ORDER BY B.itemName
FOR XML PATH('updates'), ELEMENTS, TYPE, ROOT('ranks')
;
You might want to change the location of WHERE A.lastUpdate <> 'Deleted' from the first query to the second depending on your requirement. 您可能需要根据需要将WHERE A.lastUpdate <>“已删除”的位置从第一个查询更改为第二个查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.