2017-09-01 57 views
1

總結另一列樞轉我有一個表(注:由同事使用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成一個,但需要一共有四個查詢。所以,如果有一種方法可以做到這一點,那將是驚人的!謝謝!

+1

你真的應該讀入數據庫規範化。在表格的不同列中存儲基本相似的信息是一種非常糟糕的做法。 –

+0

謝謝你的評論Erik。然而,這三列中唯一的共同信息是它們是日期類型。每欄表示一位員工稱爲某人的日期,他們有三次機會接觸某人:1)第一次約會,2)第二次約會,3)第三次約會。 – Mika

+0

他們都引用電話,他們不是嗎?你想總結它們的事實意味着它們是相關的。大多數'UNION'查詢都是非標準化數據的指標。而你因此而陷入困境。如果你將這個規範化的存儲,這個操作將需要更少的步驟,就像我將要演示的那樣。如果您想對通話日期執行操作(例如,修正某個時區),則可能需要將其應用於所有這些列,而您只需將其應用於一個列。適當規範化後,最大3個呼叫的限制將被解除。 –

回答

1

首先,我們要標準化數據,這個查詢將在以後作爲一個子查詢:

SELECT Associate, date_of_first_call as CallDate 
FROM table_name 
UNION ALL 
SELECT Associate, date_of_second_call as CallDate 
FROM table_name 
UNION ALL 
SELECT Associate, date_of_third_call as CallDate 
FROM table_name 

這是在表中存儲數據的標準化方式(可以包括數如果是第一次,第二次或第三次呼叫,請參考)。

現在,讓我們交叉表:

TRANSFORM Count(A.CallDate) AS CountOfCallDate 
SELECT A.CallDate 
FROM (
    SELECT Associate, date_of_first_call as CallDate 
    FROM table_name 
    UNION ALL 
    SELECT Associate, date_of_second_call as CallDate 
    FROM table_name 
    UNION ALL 
    SELECT Associate, date_of_third_call as CallDate 
    FROM table_name 
) As A 
GROUP BY A.CallDate 
PIVOT A.Associate 
+0

非常感謝您的幫助!它完美的工作!現在我有點理解正常化。此外,由於TRANSFORMATION語句中的語法錯誤,我將「A.CountOfCallDate」更改爲「CountOfCallDate」。 – Mika

+0

啊,是的,對不起,我會編輯答案。 –