SELECT 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
这个查询没有让我在那里。 我如何才能在一列上selectDISTINCT?
SELECT [ID],[SKU],[PRODUCT] FROM [TestData] WHERE ([PRODUCT] = (SELECT DISTINCT [PRODUCT] FROM [TestData] WHERE ([SKU] LIKE 'FOO-%')) ORDER BY [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
最简单的解决scheme是使用子查询来查找与您的查询匹配的最小ID。 在子查询中,您使用GROUP BY
而不是DISTINCT
:
SELECT * FROM [TestData] WHERE [ID] IN ( SELECT MIN([ID]) FROM [TestData] WHERE [SKU] LIKE 'FOO-%' GROUP BY [PRODUCT] )
尝试这个:
SELECT t.* FROM TestData t INNER JOIN (SELECT MIN(ID) as MinID FROM TestData WHERE SKU LIKE 'FOO-%' ) dt ON t.ID=dt.MinID
编辑
一旦OP纠正了他的samle输出(以前只有一个结果行,现在已经全部显示),这是正确的查询:
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
我知道这是6年前问的,但是知识还是知识。 这是不同的解决scheme比以上所有,因为我不得不在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
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'
尝试这个:
SELECT * FROM [TestData] WHERE Id IN(SELECT DISTINCT MIN(Id)FROM [TestData] GROUP BY Product)