總結另一列樞轉我有一個表(注:由同事使用Excel中導入)在訪問包含這樣的事情:訪問SQL合併多個列,並且在合併塔
Associate | Date_Of_First_Call | Date_of_Second_Call | Date_of_Third_Call
Amy | 07/18/2017 | 07/19/2017 | 07/20/2017
Brian | 07/18/2017 | 07/18/2017 | 07/20/2017
Amy | 07/18/2017 | 07/20/2017 |
Carl | 07/19/2017 | 07/20/2017 | 07/21/2017
我非常新以SQL從我學會爲止...
SELECT Date_Of_First_Call AS CallDate,
SUM(IIF(Associate ="Amy", 1, 0)) AS Amy,
SUM(IIF(Associate= "Brian", 1, 0)) AS Brian,
SUM(IIF(Associate="Carl", 1, 0)) AS Carl,
FROM table_name
GROUP BY Date_Of_First_Call
UNION
SELECT Date_Of_Second_Call AS CallDate,
SUM(IIF(Associate ="Amy", 1, 0)) AS Amy,
SUM(IIF(Associate= "Brian", 1, 0)) AS Brian,
SUM(IIF(Associate="Carl", 1, 0)) AS Carl,
FROM table_name
GROUP BY Date_Of_Second_Call
UNION
SELECT Date_Of_Third_Call AS CallDate,
SUM(IIF(Associate ="Amy", 1, 0)) AS Amy,
SUM(IIF(Associate= "Brian", 1, 0)) AS Brian,
SUM(IIF(Associate="Carl", 1, 0)) AS Carl,
FROM table_name
GROUP BY Date_Of_Third_Call
給我:
Call Date | Amy | Brian | Carl
07/18/2017 | 2 | 1 |
07/18/2017 | | 1 |
07/19/2017 | | | 1
07/19/2017 | 1 | |
07/20/2017 | 1 | | 1
07/20/2017 | 1 | 1 |
07/21/2017 | | | 1
關閉!但我想這不是以下:
Call Date | Amy | Brian | Carl
07/18/2017 | 2 | 2 |
07/19/2017 | 1 | | 1
07/20/2017 | 2 |1 | 1
07/21/2017 | | | 1
FYI:我能得到導致上述情況,如果我創建了三個獨立的變換/透視查詢並將其unioning成一個,但需要一共有四個查詢。所以,如果有一種方法可以做到這一點,那將是驚人的!謝謝!
你真的應該讀入數據庫規範化。在表格的不同列中存儲基本相似的信息是一種非常糟糕的做法。 –
謝謝你的評論Erik。然而,這三列中唯一的共同信息是它們是日期類型。每欄表示一位員工稱爲某人的日期,他們有三次機會接觸某人:1)第一次約會,2)第二次約會,3)第三次約會。 – Mika
他們都引用電話,他們不是嗎?你想總結它們的事實意味着它們是相關的。大多數'UNION'查詢都是非標準化數據的指標。而你因此而陷入困境。如果你將這個規範化的存儲,這個操作將需要更少的步驟,就像我將要演示的那樣。如果您想對通話日期執行操作(例如,修正某個時區),則可能需要將其應用於所有這些列,而您只需將其應用於一個列。適當規範化後,最大3個呼叫的限制將被解除。 –