gpt4 book ai didi

sql-server - 在一列上选择 DISTINCT

转载 作者:行者123 更新时间:2023-12-01 16:22:10 25 4
gpt4 key购买 nike

使用 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]

最佳答案

假设您使用的是 SQL Server 2005 或更高版本,则可以将 CTE 与 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

关于sql-server - 在一列上选择 DISTINCT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/966176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com