使用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]
答案 0 :(得分:297)
假设您使用的是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
答案 1 :(得分:40)
最简单的解决方案是使用子查询来查找与查询匹配的最小ID。在子查询中,您使用GROUP BY
而不是DISTINCT
:
SELECT * FROM [TestData] WHERE [ID] IN (
SELECT MIN([ID]) FROM [TestData]
WHERE [SKU] LIKE 'FOO-%'
GROUP BY [PRODUCT]
)
答案 2 :(得分:13)
试试这个:
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
答案 3 :(得分:8)
我知道它是在6年前被问到的,但知识仍然是知识。 这是与上述不同的解决方案,因为我必须在SQL Server 2000下运行它:
means1
答案 4 :(得分:6)
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'
答案 5 :(得分:0)
试试这个:
SELECT * FROM [TestData] WHERE Id IN(SELECT DISTINCT MIN(Id) FROM [TestData] GROUP BY Product)
答案 6 :(得分:0)
这里是一个版本,与其他几个答案基本相同,但是由于一些内联值,您可以将粘贴复制到SQL Server Management Studio中进行测试(并且不会生成任何不需要的表)。 / p>
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-%')
是作者错误代码的唯一部分,而不是问题的一部分。对于看这里的人来说不太可能有帮助。