访问SQL组合多个列并汇总另一列在组合列上进行透视

时间:2017-09-01 20:16:56

标签: sql ms-access

我在Access中有一个表(注意:从关联使用的Excel中导入),其中包含以下内容:

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

仅供参考:我可以获得上面的结果,如果我创建了三个单独的Transform / Pivot查询并将它们合并为一个,但这需要总共四个查询。所以,如果有一种方法可以做到这一点,那将是惊人的!谢谢!

1 个答案:

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