关注此question 我有......
ID SKU PRODUCT
=======================
1 FOO-23 Orange
2 BAR-23 Orange
3 FOO-24 Apple
4 FOO-25 Orange
5 FOO-25 null
6 FOO-25 null
预期结果:
1 FOO-23 Orange
3 FOO-24 Apple
5 FOO-25 null
6 FOO-25 null
这个查询并没有让我在那里。我如何SELECT DISTINCT
只在一列上消除null
中的SELECT DISTINCT
?
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
答案 0 :(得分:3)
也许有一种方法是将WITH TIES
与条件PARTITION
示例强>
Declare @YourTable Table ([ID] int,[SKU] varchar(50),[PRODUCT] varchar(50))
Insert Into @YourTable Values
(1,'FOO-23','Orange')
,(2,'BAR-23','Orange')
,(3,'FOO-24','Apple')
,(4,'FOO-25','Orange')
,(5,'FOO-25',NULL)
,(6,'FOO-25',NULL)
Select top 1 with ties *
From @YourTable
Where SKU Like 'FOO%'
Order By Row_Number() over (Partition By IsNull(Product,NewID()) Order By ID)
<强>返回强>
ID SKU PRODUCT
6 FOO-25 NULL
5 FOO-25 NULL
3 FOO-24 Apple
1 FOO-23 Orange
答案 1 :(得分:2)
这里使用John Cappelletti的样本数据是另一种方法。您真正需要的只是将OR谓词添加到where子句中。
Declare @YourTable Table ([ID] int,[SKU] varchar(50),[PRODUCT] varchar(50))
Insert Into @YourTable Values
(1,'FOO-23','Orange')
,(2,'BAR-23','Orange')
,(3,'FOO-24','Apple')
,(4,'FOO-25','Orange')
,(5,'FOO-25',NULL)
,(6,'FOO-25',NULL)
SELECT *
FROM
(
SELECT ID
, SKU
, Product
, ROW_NUMBER() OVER (PARTITION BY PRODUCT ORDER BY ID) AS RowNumber
FROM @YourTable
WHERE SKU LIKE 'FOO%'
) AS a
WHERE a.RowNumber = 1
OR a.PRODUCT IS NULL --This was the only part you were missing
答案 2 :(得分:2)
我将你的row_number改为密集排名:
Declare @YourTable Table ([ID] int,[SKU] varchar(50),[PRODUCT] varchar(50))
Insert Into @YourTable Values
(1,'FOO-23','Orange')
,(2,'BAR-23','Orange')
,(3,'FOO-24','Apple')
,(4,'FOO-25','Orange')
,(5,'FOO-25',NULL)
,(6,'FOO-25',NULL)
SELECT *
FROM (SELECT ID, SKU, Product,
Dense_RANK() OVER (PARTITION BY SKU ORDER BY Product) AS RowNumber
FROM @YourTable
WHERE left(SKU,3) = 'FOO') AS a
WHERE a.RowNumber = 1
结果:
ID SKU Product RowNumber
1 FOO-23 Orange 1
3 FOO-24 Apple 1
5 FOO-25 NULL 1
6 FOO-25 NULL 1