2014-10-31 188 views
0

試圖通過組結果波紋管:集團通過與NULL值

+-------------+------+ 
| ID | Coln1 | Coln2 | 
+-------------+------+ 
| 10 |  A | NULL | 
| 10 | NULL |  X | 
| 15 |  B | NULL | 
| 15 | NULL |  Y | 
| 20 |  C | NULL | 
| 20 | NULL |  Z | 
+--------------+-----+ 

通過以下選擇:

SELECT * FROM 
(
SELECT 
    DB1.dbo.TABLE1.id AS ID, 
    DB1.dbo.TABLE1.Coln1 AS Coln1, 
    NULL AS Coln2 
FROM 
    DB1.dbo.TABLE1 
UNION 
SELECT 
    DB2.dbo.TABLE2.id AS ID, 
    NULL AS Coln1, 
    DB2.dbo.TABLE2.Coln2 AS Coln2 
FROM 
    DB2.dbo.TABLE2 
) AS A 
GROUP BY 
    ID, 
    Coln1, 
    Coln2 
ORDER BY ID ASC 

期待這樣的:

+-------------+------+ 
| ID | Coln1 | Coln2 | 
+-------------+------+ 
| 10 |  A |  X | 
| 15 |  B |  Y | 
| 20 |  C |  Z | 
+--------------+-----+ 

沒有運氣。試圖使用一些HAVING也沒有運氣。感謝有關這方面的任何信息。

回答

3

aggregate function應該幫助你。聚合功能將消除NULL values.Try這

SELECT ID, max(Coln1), max(Coln2) 
FROM tablename 
GROUP BY 
ID 

更新您的查詢這樣的..

SELECT ID, 
     Max(Coln1), 
     Max(Coln2) 
FROM (SELECT DB1.dbo.TABLE1.id AS ID, 
       DB1.dbo.TABLE1.Coln1 AS Coln1, 
       NULL     AS Coln2 
     FROM DB1.dbo.TABLE1 
     UNION 
     SELECT DB2.dbo.TABLE2.id AS ID, 
       NULL     AS Coln1, 
       DB2.dbo.TABLE2.Coln2 AS Coln2 
     FROM DB2.dbo.TABLE2) AS A 
GROUP BY ID 
ORDER BY ID ASC 
+0

謝謝。我的情況比我發佈的例子更復雜。我正在使用帶有一些NULL列的'UNION'。要試試你的解決方案。 – Khrys 2014-10-31 17:14:27

+0

是否可以使用某種'HAVING'來解決這個問題? – Khrys 2014-10-31 17:27:50

+0

如果不查看數據,則無法發表評論。根據你的例子,沒有必要有 – 2014-10-31 17:30:28

1

你只需要改變 最大功能是用來選擇最高值&此功能是爲了避免對NULL非常helful值

SELECT ID, max(Coln1), max(Coln2) 
FROM ID, Coln1, Coln2 
GROUP BY 
ID 
0

你爲什麼這樣做工會?

SELECT 
    t1.id AS ID, 
    t1.Coln1 AS Coln1, 
    t2.Coln2 AS Coln2 

FROM 
    DB1.dbo.TABLE1 t1 

    JOIN DB2.dbo.TABLE2 t2 
     ON t1.id = t2.id