SQL question using PIVOT, no aggregation column

 

问题

https://stackoverflow.com/questions/70511664/sql-question-using-pivot-no-aggregation-column

I would like to do aPIVOTon my table but I don't have aggregation column.

SELECT

CONVERT(date, DataHora) AS dia,

CONVERT(VARCHAR(5), DataHora, 108) AS hora

FROM

[clientes].[dbo].[Tb_Ponto]

Result:

2021-12-27 12:41

2021-12-28 12:42

2021-12-28 13:03

2021-12-28 14:08

I would like it to stay like this:

2021-12-27 12:41 | NULL | NULL

2021-12-28 12:42 | 13:03 | 14:08

解答

对日期、时间有序的数据,按日期分组,添加组内序号,然后行转列即可。SQL的问题在于pivot(… in(column_list)),其中column_list是必须指定的,简单场景可以写死,但是当列数较多或者不确定时,需要写存储过程动态生成,非常麻烦。通常的办法是读出来用PythonSPL来做, SPL(一种 Java 的开源包)更容易被Java应用集成,代码也更简单一点,只要两句:


A

1

=MSSQL.query("SELECT CONVERT(date, DataHora) AS dia,CONVERT(VARCHAR(5), DataHora, 108)AS hora FROM [clientes].[dbo].[Tb_Ponto] ORDER BY 1,2")

2

=A1.derive("hora"/ranki(#2;#1):fn).pivot(#1;#3,#2)

SPL源代码:https://github.com/SPLWare/esProc

问答搜集