我的问题是如何从规范化表格中创建非规范化(OLAP)表格。
我有一些带有一些数据的OLTP数据库。见下图:
特别注意表“Variable”,“Variable_Value”和“Variable_Sample”。
可变
VARIABLE_VALUE:
Variable_Sample:
创建表“Variable_Sample”的脚本见下文:
ALTER PROCEDURE [dbo].[VarSample]
AS
BEGIN
truncate table UIR_DB.dbo.Variable_Sample
Declare params cursor for
Select distinct id_variable from UIR_DB.dbo.Variable_Value
open params
Declare @idparam int
Declare @csql nvarchar(max) = ''
Declare @csql2 nvarchar(max) = ''
Declare @i int = 1
fetch next from params into @idparam
while @@FETCH_STATUS = 0
begin
Select @csql2 = @csql2 + ', param' +LTrim(Str(@i))
Select @csql = @csql + ' (Select value as param'+LTrim(Str(@i))+' from UIR_DB.dbo.Variable_Value where id_variable = '+LTrim(Str(@idparam))+') a'+LTrim(Str(@i))+' cross join'
Set @i = @i+1
fetch next from params into @idparam
end
Select @csql = '
Insert INTO UIR_DB.dbo.Variable_Sample SELECT id, CAST(SubString(Param,6,LEN(Param)-5) as int) param_id, param_val
FROM
(Select ROW_Number() over(order by '+SubString(@csql2,2,LEN(@csql2)-1)+') id, '+SubString(@csql2,2,LEN(@csql2)-1)+' from '+SubString(@csql,1,LEN(@csql)-11) + ') p
UNPIVOT
(param_val FOR Param IN
('+SubString(@csql2,2,LEN(@csql2)-1)+')
)AS unpvt
'
print @csql
exec sp_executesql @csql
delete from Sample
Insert into Sample select distinct UIR_DB.dbo.Variable_Sample.idsample from UIR_DB.dbo.Variable_Sample
close params
deallocate params
END
我需要创建表格,类似“Variable_Sample_Olap”格式:
Variable_Sample_Olap:
(当然,如果它是variable3,...,variableN,那么它将是“Variable_Sample_Olap”中的N列。)
有人可以通过脚本帮助我改变Variable_Sample_Olap中的Variable_Sample吗?