Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 如何在SQL Server中仅获取一个相同ID的项?_Sql Server - Fatal编程技术网

Sql server 如何在SQL Server中仅获取一个相同ID的项?

Sql server 如何在SQL Server中仅获取一个相同ID的项?,sql-server,Sql Server,我有一个表,名称为产品: ProductId ProductName CategoryId 1 Tshirt 1 2 Jeans 1 3 Tops 2 4 Lipstick 2 我想要这样的输出: ProductId ProductName CategoryId 1 Tshir

我有一个表,名称为产品:

ProductId    ProductName    CategoryId
   1            Tshirt        1
   2            Jeans         1
   3            Tops          2
   4            Lipstick      2 
我想要这样的输出:

ProductId    ProductName   CategoryId
 1             Tshirt            1
 3              Tops             2

这意味着每个类别只有一个项目。是否可以使用SQL查询执行此操作?

您可以使用RowNumber()函数,但按照我的使用方式,它将为每个CategoryID随机选择第一个产品

如果您想更好地控制应选择的产品名称,请使用适当的
orderbycolumnname
,而不是
orderby(选择NULL)


您可以使用RowNumber()函数,但按照我使用它的方式,它将为每个CategoryID随机选择第一个产品

如果您想更好地控制应选择的产品名称,请使用适当的
orderbycolumnname
,而不是
orderby(选择NULL)


使用窗口功能:

WITH AdditionalNumbering AS
(
    SELECT ProductId, ProductName, CategoryID,
    ROW_NUMBER() OVER (PARTITION BY CategoryID ORDER BY ProductID) RowNumber
)
SELECT ProductId, ProductName, CategoryID
FROM AdditionalNumbering
WHERE RowNumber=1

使用窗口功能:

WITH AdditionalNumbering AS
(
    SELECT ProductId, ProductName, CategoryID,
    ROW_NUMBER() OVER (PARTITION BY CategoryID ORDER BY ProductID) RowNumber
)
SELECT ProductId, ProductName, CategoryID
FROM AdditionalNumbering
WHERE RowNumber=1

似乎你更快:)似乎你更快:)