如何将行转换为按行数创建标题的列
Posted
技术标签:
【中文标题】如何将行转换为按行数创建标题的列【英文标题】:How to convert rows to columns creating headers by rowcount 【发布时间】:2019-08-01 21:14:58 【问题描述】:我正在从时钟记录列表创建员工上班/下班报告。
我尝试使用 SQL Pivot、c# 和 javascript 循环,但无法确定。 这是我尝试过的一些,不知道用什么代替“Max”,因为我需要每条记录。
SELECT *
FROM
(
SELECT cast (ClockTime as date) as Date ,
xrefnumber as EmployeeNo,
ClockTime
FROM #log
) AS SourceTable PIVOT(max(ClockTime) FOR ClockTime IN([ClockTime1],
[ClockTime2],
[ClockTime3],
[ClockTime4],
[ClockTime5],
[ClockTime6],
[ClockTime7],
[ClockTime8],
[ClockTime9],
[ClockTime10])) AS PivotTable;
这是我的数据
Date EmplooyeeNo ClockTime
---------- ------- -----------------------
2019-06-10 0000010 2019-06-10 05:58:35.000
2019-06-10 0000010 2019-06-10 06:04:59.000
2019-06-10 0000010 2019-06-10 06:14:38.000
2019-06-10 0000010 2019-06-10 11:19:13.000
2019-06-10 0000010 2019-06-10 11:30:28.000
2019-06-10 0000010 2019-06-10 11:34:25.000
2019-06-10 0000010 2019-06-10 11:48:00.000
2019-06-11 0000010 2019-06-11 12:29:04.000
2019-06-11 0000010 2019-06-11 12:30:56.000
2019-06-11 0000010 2019-06-11 12:42:06.000
2019-06-11 0000010 2019-06-11 12:42:30.000
2019-06-10 0000018 2019-06-10 11:48:06.000
2019-05-30 0120485 2019-05-30 10:30:11.000
2019-05-30 0120485 2019-05-30 10:33:39.000
2019-05-30 0120485 2019-05-30 10:34:10.000
2019-05-30 0120485 2019-05-30 10:36:09.000
2019-05-30 0120485 2019-05-30 10:38:21.000
2019-05-30 0120485 2019-05-30 10:38:30.000
2019-05-30 0120485 2019-05-30 10:43:07.000
2019-05-30 0120485 2019-05-30 10:43:29.000
这是理想的输出
Date EmplooyeeNo ClockTime1 ClockTime2 ClockTime3 ClockTime4 ClockTime5 ClockTime6 ClockTime7 ClockTime8
2019-06-10 0000010 2019-06-10 05:58:35.000 2019-06-10 06:04:59.000 2019-06-10 06:14:38.000 2019-06-10 11:19:13.000 2019-06-10 11:30:28.000 2019-06-10 11:34:25.000 2019-06-10 11:48:00.000
2019-06-11 0000010 2019-06-11 12:29:04.000 2019-06-11 12:30:56.000 2019-06-11 12:42:06.000 2019-06-11 12:42:30.000
2019-06-10 0000018 2019-06-10 11:48:06.000
2019-05-30 0120485 2019-05-30 10:30:11.000 2019-05-30 10:33:39.000 2019-05-30 10:34:10.000 2019-05-30 10:36:09.000 2019-05-30 10:38:21.000 2019-05-30 10:38:30.000 2019-05-30 10:43:07.000 2019-05-30 10:43:29.000
如果必须指定列数量就可以了。
【问题讨论】:
【参考方案1】:这应该可以得到你想要的。我基本上只是按 EmployeeNo 和 ClockTime 日期对这些值进行了分组,这样你就有了一个值得关注的值。
SELECT
*
FROM
(
SELECT
CAST(ClockTime AS DATE) AS [Date]
,xrefnumber AS EmployeeNo
,ClockTime
,'ClockTime' + CAST(ROW_NUMBER() OVER(PARTITION BY xrefnumber, CAST(ClockTime AS DATE) ORDER BY ClockTime ASC) AS VARCHAR(3)) AS ClockTimeDesc
FROM
#log
) AS SourceTable
PIVOT
(MAX(ClockTime) FOR ClockTimeDesc IN([ClockTime1], [ClockTime2], [ClockTime3], [ClockTime4], [ClockTime5], [ClockTime6], [ClockTime7], [ClockTime8])) AS PivotTable
【讨论】:
以上是关于如何将行转换为按行数创建标题的列的主要内容,如果未能解决你的问题,请参考以下文章
如何在Oracle sql中将行转换为按多列分组的列[关闭]
如何使用枢轴将行转换为postgres中的列?让我来计算一下