在SQL中使用相对列名值计算DATE值



我有一个表,它有一些特殊的数据安排,其中有28-31列对应于一系列唯一id的月份的日期。我要做的是用实际的日期值把它变成更可行的格式。我的表如下所示:

DECLARE @Month VARCHAR(3) 
SET @Month = 'NOV'
353Z

一个选择是使用JSON来"动态地";取消数据透视

Select A.[ID]
,A.[Status]
,[Date] = datefromparts(2022,11,[key])
,Value
From  YourTable A
Cross Apply  (
Select [Key]
,[Value]
From  OpenJson(  (Select A.* For JSON Path,Without_Array_Wrapper )  ) 
Where [Key] not in ('ID','Status')
) B

结果

ID  Status  Date        Value
111 Active  2022-11-01  A
111 Active  2022-11-02  2
111 Active  2022-11-03  3
111 Active  2022-11-04  4
111 Active  2022-11-05  Z

最新更新