Sql-Server

JOIN/Union 兩個表,盡可能去掉NULL(類似於pandas concatenate)

  • May 5, 2020

如果您熟悉Pandas,我想知道如何執行我認為最類似於連接的操作。

基本上,我想做的似乎是一個 UNION,其中記錄在某種意義上被“折疊”以刪除 NULL 值(也就是說,ID 和 DATE 是相同的)。我嘗試了 UNION、FULL JOIN 和 SELF JOIN,但這些似乎都沒有產生預期的結果。似乎 MSSQL 的 MERGE 可能是我正在尋找的?但是,該操作似乎是為了創建表。

我的最終目標基本上是從結果中創建一個視圖。我真正需要的是允許我進行進一步操作的 SELECT 語句。

為了幫助視覺化問題,假設我有下表:

+----+--------+-------------+---------------+
| ID | Date   | FloorRating | CeilingRating |
+----+--------+-------------+---------------+
| 1A | 1/1/18 | 9           | 6             |
+----+--------+-------------+---------------+
| 1A | 1/1/19 | 9           | 7             |
+----+--------+-------------+---------------+
| 3D | 2/2/19 | 5           | 8             |
+----+--------+-------------+---------------+
| 3D | 3/3/19 | 4           | 9             |
+----+--------+-------------+---------------+


+----+--------+--------------+-----------+
| ID | Date   | WindowRating | FanRating |
+----+--------+--------------+-----------+
| 1A | 1/1/18 | 4            | 7         |
+----+--------+--------------+-----------+
| 1A | 2/2/19 | 3            | 7         |
+----+--------+--------------+-----------+
| 3D | 2/2/19 | 9            | 4         |
+----+--------+--------------+-----------+
| 3D | 8/8/19 | 1            | 3         |
+----+--------+--------------+-----------+

我想要結束的是這樣的事情,其中​​考慮了所有可能的 ID-Date 組合,並在可能的情況下填寫欄位值:

+----+--------+-------------+---------------+--------------+-----------+
| ID | Date   | FloorRating | CeilingRating | WindowRating | FanRating |
+----+--------+-------------+---------------+--------------+-----------+
| 1A | 1/1/18 | 9           | 6             | 4            | 7         |
+----+--------+-------------+---------------+--------------+-----------+
| 1A | 1/1/19 | 9           | 7             |              |           |
+----+--------+-------------+---------------+--------------+-----------+
| 1A | 2/2/19 |             |               | 3            | 7         |
+----+--------+-------------+---------------+--------------+-----------+
| 3D | 2/2/19 | 5           | 8             | 9            | 4         |
+----+--------+-------------+---------------+--------------+-----------+
| 3D | 3/3/19 | 4           | 9             |              |           |
+----+--------+-------------+---------------+--------------+-----------+
| 3D | 8/8/19 |             |               | 1            | 3         |
+----+--------+-------------+---------------+--------------+-----------+

感謝您提供的任何幫助或提示!

我嘗試了 UNION、FULL JOIN 和 SELF JOIN,但這些似乎都沒有產生預期的結果

FULL JOIN工作正常。也許您加入了錯誤的謂詞,或者沒有合併IDandDate列的結果(在ISNULL下面完成)?

db <> 小提琴

SELECT ISNULL(T1.[ID], T2.[ID]) AS [ID],
      ISNULL(T1.Date, T2.Date) AS Date,
      [FloorRating],
      [CeilingRating],
      [WindowRating],
      [FanRating]
FROM   Table1 T1
      FULL JOIN Table2 T2
             ON T1.[ID] = T2.[ID]
                AND T1.[Date] = T2.[Date]
ORDER  BY [ID],
         Date 

引用自:https://dba.stackexchange.com/questions/266533