我有以下示例数据:
ID Name Street Number Code
100 John Street1 1 1234
130 Peter Street1 2 1234
135 Bob Street2 1 5678
141 Alice Street5 3 5678
160 Sara Street1 3 3456
现在我需要一个Query来只返回最后一条记录,因为它的Code是唯一的。
答案 0 :(得分:5)
您可以使用GROUP BY
和HAVING
的查询确定哪些代码是唯一的。
SELECT [Code]
FROM YourTable
GROUP BY [Code]
HAVING Count(*) = 1;
要获取与这些唯一[Code]
值匹配的完整行,请将该查询加回到您的表中。
SELECT y.*
FROM
YourTable AS y
INNER JOIN
(
SELECT [Code]
FROM YourTable
GROUP BY [Code]
HAVING Count(*) = 1
) AS sub
ON y.Code = sub.Code;
答案 1 :(得分:1)
感谢HansUp,这是我现在的最后一个问题:
SELECT
A.*
FROM
(T_NEEDED AS A
INNER JOIN
(
SELECT
CODE
FROM
T_NEEDED
GROUP BY
CODE
HAVING
Count(*) = 1
) AS B
ON
A.CODE = B.CODE)
LEFT OUTER JOIN
T_UNNEEDED AS C
ON
A.ID = C.ID
WHERE
C.ID Is Null
ORDER BY
A.NAME,
A.STREET,
A.NUMBER
说明:我有两个表,一个包含需要ID的记录和一个不需要的记录。不需要的ID可能在所需的表中,如果它们是我希望它们被排除,因此LEFT OUTER JOIN。然后是第二部分打开了问题。我想从具有不唯一的代码或也属于其他ID的代码中排除这些记录。
结果是一个只包含所需ID的表,在此表中每个代码都是唯一的。
答案 2 :(得分:0)
您可以尝试使用CTE:
WITH tempTbl
AS ( SELECT ROW_NUMBER() OVER ( PARTITION BY code ORDER BY code ) AS rownm, *
FROM yourtable
)
SELECT * FROM tempTbl WHERE code NOT IN (SELECT code FROM tempTbl WHERE rownm > 1)