Также вы можете попробовать использовать unpivot для достижения ваших требований.Для более подробной информации, вы можете обратиться к этой статье: https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017
----drop table [current_table]
----drop table [definition]
create table [current_table]
(p1 int,
p2 int,
p3 int,
p4 int,
ts date )
insert into [current_table] values
(5,null,null,null,'20181206'),
(null,88,null,null,'20181101'),
(null,18,null,null,'20181018'),
(null,null,32,null,'20181027'),
(null,null,null,6,'20181014')
create table [definition]
(id int,
name varchar(5) )
insert into [definition] values
(1,'p1'),(2,'p2'),
(3,'p3'),(4,'p4')
;with cte as (
SELECT [name] ,[count],ts
FROM [current_table] t
UNPIVOT ([count] FOR [name] IN ([p1],[p2],[p3],[p4])) u)
select b.id,a.count,a.ts from cte a join [definition] b on a.name=b.name
/*
id count ts
----------- ----------- ----------
1 5 2018-12-06
2 88 2018-11-01
2 18 2018-10-18
3 32 2018-10-27
4 6 2018-10-14
*/
------dynamic-------------
DECLARE @ColNames varchar(1000);
SET @ColNames = '';
SELECT @ColNames =stuff((
SELECT DISTINCT ',' + QUOTENAME(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS p2
WHERE TABLE_NAME = 'current_table'
AND COLUMN_NAME like 'p%'
FOR XML PATH(''), TYPE).value('.', 'varchar(max)')
,1,1,'')
DECLARE @CMD nvarchar(2000);
SET @CMD = ';with cte as (
SELECT [name] ,[count],ts
FROM [current_table] t
UNPIVOT ([count] FOR [name] IN ('+@ColNames+')) u)
select b.id,a.count,a.ts from cte a join [definition] b on a.name=b.name'
PRINT @CMD
execute sp_executesql @CMD
/*
;with cte as (
SELECT [name] ,[count],ts
FROM [current_table] t
UNPIVOT ([count] FOR [name] IN ([p1],[p2],[p3],[p4])) u)
select b.id,a.count,a.ts from cte a join [definition] b on a.name=b.name
id count ts
----------- ----------- ----------
1 5 2018-12-06
2 88 2018-11-01
2 18 2018-10-18
3 32 2018-10-27
4 6 2018-10-14
*/
Надеюсь, что это может помочь вам.
С наилучшими пожеланиями,
Рейчел