在一列上选择Distinct并消除Select Distinct中的空值?

时间:2018-01-16 14:36:11

标签: sql-server tsql

关注此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

3 个答案:

答案 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