我有一个包含以下列的表格:
GLLink int
Budget01 float
Budget02 float
Budget03 float
Budget04 float
Budget05 float
Budget06 float
Budget07 float
...
Budget57 float
Budget58 float
Budget59 float
Budget60 float
由于我的过滤器,每列有8行。
所有这些列都有值。
我需要将每个列的值设置为零,但是我了解到我需要先对数据进行透视,然后再进行更新?
我知道您可以在Excel中transpose
进行查询,然后在Excel中开发查询,但是,我想知道如何在不使用Excel的情况下实现这一目标。
在Excel中进行转置后,我的更新查询将如下所示:
update Budgets set Budget01 = 0 where GLLink in (select AccountLink from Accounts where Master_Sub_Account like '3200>%')
update Budgets set Budget02 = 0 where GLLink in (select AccountLink from Accounts where Master_Sub_Account like '3200>%')
update Budgets set Budget03 = 0 where GLLink in (select AccountLink from Accounts where Master_Sub_Account like '3200>%')
update Budgets set Budget04 = 0 where GLLink in (select AccountLink from Accounts where Master_Sub_Account like '3200>%')
update Budgets set Budget05 = 0 where GLLink in (select AccountLink from Accounts where Master_Sub_Account like '3200>%')
update Budgets set Budget06 = 0 where GLLink in (select AccountLink from Accounts where Master_Sub_Account like '3200>%')
update Budgets set Budget07 = 0 where GLLink in (select AccountLink from Accounts where Master_Sub_Account like '3200>%')
...
update Budgets set Budget57 = 0 where GLLink in (select AccountLink from Accounts where Master_Sub_Account like '3200>%')
update Budgets set Budget58 = 0 where GLLink in (select AccountLink from Accounts where Master_Sub_Account like '3200>%')
update Budgets set Budget59 = 0 where GLLink in (select AccountLink from Accounts where Master_Sub_Account like '3200>%')
update Budgets set Budget60 = 0 where GLLink in (select AccountLink from Accounts where Master_Sub_Account like '3200>%')
我如何在不使用Excel且不考虑所有上述因素的情况下,用SQL开发相同的更新查询?
答案 0 :(得分:1)
使用一个更新来全部统治
update Budgets
set
Budget01 = 0,
Budget02 = 0,
Budget03 = 0,
...
Budget59 = 0,
Budget60 = 0
where GLLink in (select AccountLink from Accounts where Master_Sub_Account like '3200>%')
或使用动态SQL
示例:
declare @Cols NVARCHAR(max);
declare @DynSql NVARCHAR(max);
SELECT @Cols = concat(@Cols+', ',char(10), Col.Name, '=0')
FROM SYS.OBJECTS Obj
JOIN SYS.COLUMNS Col ON Obj.OBJECT_ID = Col.OBJECT_ID
WHERE Obj.TYPE='U'
AND Obj.NAME = 'Budgets'
AND Col.Name LIKE 'Budget[0-9][0-9]';
set @DynSql = N'update Budgets set '+ @Cols + char(10) +
'where GLLink in (select AccountLink from Accounts where Master_Sub_Account like ''3200>%'')';
exec(@DynSql);
在 db <>小提琴here
上进行测试