在一列上选择DISTINCT

使用SQL Server,我有…

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 ?

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

试试这个:

SELECT
t.*
FROM TestData t
INNER JOIN (SELECT
MIN(ID) as MinID
FROM TestData
WHERE SKU LIKE 'FOO-%'
) dt ON t.ID=dt.MinID
< p > 编辑 < br > 一旦OP纠正了他的样本输出(以前只有一个结果行,现在显示了所有结果行),这是正确的查询:

declare @TestData table (ID int, sku char(6), product varchar(15))
insert into @TestData values (1 ,  'FOO-23'      ,'Orange')
insert into @TestData values (2 ,  'BAR-23'      ,'Orange')
insert into @TestData values (3 ,  'FOO-24'      ,'Apple')
insert into @TestData values (4 ,  'FOO-25'      ,'Orange')


--basically the same as @Aaron Alton's answer:
SELECT
dt.ID, dt.SKU, dt.Product
FROM (SELECT
ID, SKU, Product, ROW_NUMBER() OVER (PARTITION BY PRODUCT ORDER BY ID) AS RowID
FROM @TestData
WHERE  SKU LIKE 'FOO-%'
) AS dt
WHERE dt.RowID=1
ORDER BY dt.ID

假设您使用的是SQL Server 2005或更高版本,您可以使用带有ROW_NUMBER()的CTE:

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
SELECT min (id) AS 'ID', min(sku) AS 'SKU', Product
FROM TestData
WHERE sku LIKE 'FOO%' -- If you want only the sku that matchs with FOO%
GROUP BY product
ORDER BY 'ID'

最简单的解决方案是使用子查询来查找与查询匹配的最小ID。在子查询中使用GROUP BY而不是DISTINCT:

SELECT * FROM [TestData] WHERE [ID] IN (
SELECT MIN([ID]) FROM [TestData]
WHERE [SKU] LIKE 'FOO-%'
GROUP BY [PRODUCT]
)

试试这个:

< p > SELECT * FROM [TestData] WHERE Id IN(SELECT DISTINCT MIN(Id) FROM [TestData] GROUP BY Product) < / p >才能
我知道6年前有人问过这个问题,但知识还是知识。 这是不同于上面所有的解决方案,因为我必须在SQL Server 2000下运行它:

DECLARE @TestData TABLE([ID] int, [SKU] char(6), [Product] varchar(15))
INSERT INTO @TestData values (1 ,'FOO-23', 'Orange')
INSERT INTO @TestData values (2 ,'BAR-23', 'Orange')
INSERT INTO @TestData values (3 ,'FOO-24', 'Apple')
INSERT INTO @TestData values (4 ,'FOO-25', 'Orange')


SELECT DISTINCT  [ID] = ( SELECT TOP 1 [ID]  FROM @TestData Y WHERE Y.[Product] = X.[Product])
,[SKU]= ( SELECT TOP 1 [SKU] FROM @TestData Y WHERE Y.[Product] = X.[Product])
,[PRODUCT]
FROM @TestData X

下面是一个版本,基本上与其他几个答案相同,但是由于一些内联值,您可以将其复制粘贴到SQL server Management Studio中进行测试(并且不会生成任何不需要的表)。

WITH [TestData]([ID],[SKU],[PRODUCT]) AS
(
SELECT *
FROM (
VALUES
(1,   'FOO-23',  'Orange'),
(2,   'BAR-23',  'Orange'),
(3,   'FOO-24',  'Apple'),
(4,   'FOO-25',  'Orange')
)
AS [TestData]([ID],[SKU],[PRODUCT])
)


SELECT * FROM [TestData] WHERE [ID] IN
(
SELECT MIN([ID])
FROM [TestData]
GROUP BY [PRODUCT]
)

结果

ID  SKU     PRODUCT
1   FOO-23  Orange
3   FOO-24  Apple

我忽略了以下几点…

WHERE ([SKU] LIKE 'FOO-%')

因为这只是作者错误代码的一部分,而不是问题的一部分。这对找这里的人没什么帮助。