我在这里阅读了很多文章,试图弄清楚如何使用此透视功能,但没有运气。某些解释中有些对我来说是不必要的,或者由于我只是最近才开始自学SQL而变得难以理解。
我需要弄清楚如何将我的日期分组为一个日期,然后将P1,P2,P3 ...分成几列。最重要的是将P1-10放在每个单独的列中。
这就是原始SQL Server的样子。.+许多其他列与我要执行的操作无关。
+-------------+------------+---------------------+
| StationName | Start_Time | Time |
+-------------+------------+---------------------+
| P1 | 15 | 2018-06-21 13:37:34 |
+-------------+------------+---------------------+
| P3 | 69 | 2018-06-21 12:33:55 |
+-------------+------------+---------------------+
| P4 | 52 | 2018-06-21 13:42:34 |
+-------------+------------+---------------------+
| P1 | 18 | 2018-06-21 10:37:34 |
+-------------+------------+---------------------+
| P9 | 78 | 2018-06-21 6:37:34 |
+-------------+------------+---------------------+
This is what I currently have
SELECT Cast(Start_Time AS DATE) AS Date,
StationName,
sum(time) AS "Daily Downtime"
FROM A6K_Events
Where StationName Like 'P%'
GROUP BY Cast(Start_Time AS DATE), StationName
Order By Date DESC
+------------+-------------+----------------+
| Date | StationName | Daily Downtime |
+------------+-------------+----------------+
| 2018-06-21 | P1 | 33 |
+------------+-------------+----------------+
| 2018-06-21 | P3 | 62 |
+------------+-------------+----------------+
| 2018-06-21 | P8 | 1 |
+------------+-------------+----------------+
| 2018-06-21 | P9 | 78 |
+------------+-------------+----------------+
| 2018-06-20 | P1 | 69 |
+------------+-------------+----------------+
| 2018-06-19 | P1 | 52 |
+------------+-------------+----------------+
This is what I would like to have:
+------------+----+----+----+----+----+----+----+----+----+-----+
| Date | P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 |
+------------+----+----+----+----+----+----+----+----+----+-----+
| 2018-06-21 | 33 | | 62 | | | | | 1 | 78 | |
+------------+----+----+----+----+----+----+----+----+----+-----+
| 2018-06-20 | 69 | | | | | | | | | |
+------------+----+----+----+----+----+----+----+----+----+-----+
| 2018-06-19 | 52 | | | | | | | | | |
+------------+----+----+----+----+----+----+----+----+----+-----+
填写的数字将是当天该进程的“每日停机时间”值。最终结果将被实时记录,并包含许多日期和各种停机时间。
谢谢您的帮助
已编辑以添加文本表和删除图像
答案 0 :(得分:2)
您可以使用以下数据透视表语句完成输出。
SELECT * FROM(
SELECT CAST([Start_Date] AS DATE) as [DATE],SUM(TIME) AS [Daily DownTime],STATIONNAME FROM A6K_Events Where StationName Like 'P%' GROUP BY [start_date],STATIONNAME
) AS S
PIVOT(sum([Daily DownTime]) FOR STATIONNAME IN([P1],[P2],[P3],[P4],[P5],[P6],[P7],[P8],[P9],[P10])) AS PT