我有一个访问表(称为year2016),其中包含月份列和客户名称行,以及在本月进行过启动操作的工作人员姓名。我想要sql代码,该代码可以让我每个工人每月处理多少个客户。
表格如下:
client month01 month02 month03 month04 .......
1 john adam sarah john
2 adam adam john sarah
.
.
.
我是sql的新手,我尝试了此操作(同时进行了两个月),但它给了我错误:
SELECT a.name, c1.count, c2.count
FROM (SELECT month01 AS name FROM year2016 UNION SELECT month02 FROM year2016) a
LEFT JOIN (SELECT month01, COUNT(*) AS count FROM year2016 GROUP BY month01) c1
ON a.name=c1.month01
LEFT JOIN (SELECT month02, COUNT(*) AS count FROM year2016 GROUP BY month02) c2
On a.name=c2.month02;
我希望得到这样的表:
worker month01 month02 month03 month04 ......
john 8 14 5 9
adam 12 6 5 3
sarah 4 6 34 56
答案 0 :(得分:2)
一种方法可能是先将所有月份列合并为一个列,然后按月份进行透视:
SELECT
worker,
SUM(IIF(month='month01', 1, 0)) AS month01,
SUM(IIF(month='month02', 1, 0)) AS month02,
SUM(IIF(month='month03', 1, 0)) AS month03,
SUM(IIF(month='month04', 1, 0)) AS month04,
SUM(IIF(month='month05', 1, 0)) AS month05,
SUM(IIF(month='month06', 1, 0)) AS month06,
SUM(IIF(month='month07', 1, 0)) AS month07,
SUM(IIF(month='month08', 1, 0)) AS month08,
SUM(IIF(month='month09', 1, 0)) AS month09,
SUM(IIF(month='month10', 1, 0)) AS month10,
SUM(IIF(month='month11', 1, 0)) AS month11,
SUM(IIF(month='month12', 1, 0)) AS month12
FROM
(
SELECT month01 AS worker, 'month01' AS month FROM year2016 UNION ALL
SELECT month02, 'month02' FROM year2016 UNION ALL
SELECT month03, 'month03' FROM year2016 UNION ALL
SELECT month04, 'month04' FROM year2016 UNION ALL
SELECT month05, 'month05' FROM year2016 UNION ALL
SELECT month06, 'month06' FROM year2016 UNION ALL
SELECT month07, 'month07' FROM year2016 UNION ALL
SELECT month08, 'month08' FROM year2016 UNION ALL
SELECT month09, 'month09' FROM year2016 UNION ALL
SELECT month10, 'month10' FROM year2016 UNION ALL
SELECT month11, 'month11' FROM year2016 UNION ALL
SELECT month12, 'month12' FROM year2016
) t
GROUP BY
worker;
但是请注意,您的数据完全没有规范化。我在上面别名为t
的子查询实际上就是您应该如何在Access中存储数据。因此,请尝试更改您的设计。