如何通过一列选择不同的?

时间:2017-10-16 12:56:29

标签: sql sql-server tsql null distinct

我有一个包含下面列的表,如果COD重复,我需要获取值,在VALUE列上获取非NULL。如果不重复,则可以获得NULL VALUE。像例子一样:

我正在使用SQL SERVER。

这就是我得到的:

COD ID  VALUE
28  1   NULL
28  2   Supermarket
29  1   NULL
29  2   School
29  3   NULL
30  1   NULL

这就是我想要的:

COD ID  VALUE
28  2   Supermarket
29  2   School
30  1   NULL

我正在尝试做什么:

;with A as (    
(select DISTINCT COD,ID,VALUE from CodId where ID = 2)  
UNION   
(select DISTINCT COD,ID,NULL from CodId where ID != 2) 
)select * from A order by COD

4 个答案:

答案 0 :(得分:8)

你可以试试这个。

DECLARE @T TABLE (COD INT, ID INT,  VALUE VARCHAR(20))
INSERT INTO @T 

VALUES(28,  1,   NULL),
(28,  2   ,'Supermarket'),
(29,  1   ,NULL),
(29,  2   ,'School'),
(29,  3   ,NULL),
(30,  1   ,NULL)


;WITH CTE AS (
SELECT *, RN= ROW_NUMBER() OVER (PARTITION BY COD ORDER BY VALUE DESC) FROM @T
)
SELECT COD, ID ,VALUE  FROM CTE
WHERE RN = 1

结果:

COD         ID          VALUE
----------- ----------- --------------------
28          2           Supermarket
29          2           School
30          1           NULL

答案 1 :(得分:5)

另一种选择是与Row_Number()

一起使用Select top 1 with ties * from YourTable Order By Row_Number() over (Partition By [COD] order by Value Desc) 子句

示例

COD ID  VALUE
28  2   Supermarket
29  2   School
30  1   NULL

<强>返回

{{1}}

答案 2 :(得分:1)

我会使用GROUP BYJOIN。如果NOT NULL的值不是COD,则应使用OR子句中的JOIN来解析。

 SELECT your_table.* 
 FROM your_table
 JOIN (
    SELECT COD, MAX(value) value
    FROM your_table
    GROUP BY COD
 ) gt ON your_table.COD = gt.COD and (your_table.value = gt.value OR gt.value IS NULL)

答案 3 :(得分:1)

如果您的COD可能有多个非空值,则可以使用

drop table MyTable

CREATE TABLE MyTable
  (
     COD   INT,
     ID    INT,
     VALUE VARCHAR(20)
  )

INSERT INTO MyTable
VALUES      (28,1, NULL),
            (28,2,'Supermarket'),
            (28,3,'School'),
            (29,1,NULL),
            (29,2,'School'),
            (29,3,NULL),
            (30,1,NULL);

WITH Dups AS
    (SELECT  COD FROM MyTable GROUP BY COD  HAVING count (*) > 1 )

    SELECT MyTable.COD,MyTable.ID,MyTable.VALUE FROM MyTable
    INNER JOIN dups ON MyTable.COD = Dups.COD
    WHERE value IS NOT NULL
    UNION
    SELECT MyTable.COD,MyTable.ID,MyTable.VALUE FROM MyTable
    LEFT JOIN dups ON MyTable.COD = Dups.COD
    WHERE dups.cod IS NULL