2017-10-16 92 views
5

我有一個表,下面的列,我需要得到的值,如果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 

回答

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

我會用GROUP BYJOIN。如果COD的值沒有NOT NULL,則應該使用JOIN子句中的OR來解決。

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) 
5

另一種選擇是使用在音樂會的WITH TIES子句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

如果你可以爲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