使用空值分组

时间:2014-10-31 17:03:46

标签: sql sql-server

尝试按结果分组:

+-------------+------+
| 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 个答案:

答案 0 :(得分:3)

aggregate function可以帮到你。聚合函数将消除NULL值。请尝试此

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 

答案 1 :(得分:1)

你只需要改变 最大功能用于选择最高值和最大值。这个函数非常有助于避免使用NULL值

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

答案 2 :(得分: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