在一列上选择 DISTINCT

2021-12-02 00:00:00 sql distinct tsql sql-server

使用 SQL Server,我有...

Using SQL Server, I have...

ID  SKU     PRODUCT
=======================
1   FOO-23  Orange
2   BAR-23  Orange
3   FOO-24  Apple
4   FOO-25  Orange

我想要

1   FOO-23  Orange
3   FOO-24  Apple

这个查询并没有让我到达那里.如何仅对一列选择 DISTINCT?

This query isn't getting me there. How can I SELECT DISTINCT on just one column?

SELECT 
[ID],[SKU],[PRODUCT]
FROM [TestData] 
WHERE ([PRODUCT] = 
(SELECT DISTINCT [PRODUCT] FROM [TestData] WHERE ([SKU] LIKE 'FOO-%')) 
ORDER BY [ID]

推荐答案

假设您使用的是 SQL Server 2005 或更高版本,您可以将 CTE 与 ROW_NUMBER() 一起使用:

Assuming that you're on SQL Server 2005 or greater, you can use a CTE with ROW_NUMBER():

SELECT  *
FROM    (SELECT ID, SKU, Product,
                ROW_NUMBER() OVER (PARTITION BY PRODUCT ORDER BY ID) AS RowNumber
         FROM   MyTable
         WHERE  SKU LIKE 'FOO%') AS a
WHERE   a.RowNumber = 1

相关文章