34,594
社区成员
发帖
与我相关
我的任务
分享
--查询右上角至左下角对角线数字之和
declare @sql varchar(max)
set @sql='select '
select @sql=@sql+'(select isnull('+name+','''') from T where id='+cast((select max(column_id) from sys.columns where object_id=object_id('T'))-column_id+1 as varchar(20))+
case when column_id=(select max(column_id) from sys.columns where object_id=object_id('T')) then ')' else ')+' end
from sys.columns where object_id=object_id('T') and column_id>1 order by column_id asc
select @sql
exec(@sql)
---
34
use tempdb
go
if object_id('tempdb.dbo.T') is not null drop table T
create table T (id int identity(1,1) primary key,a int,b int,c int,d int)
insert into T
select 1, 2, 3, 4 union all
select 5, 6, 7, 8 union all
select 9,10,11,12 union all
select 13,14,15,16
--查询左上角至右下角对角线数字之和
declare @sql varchar(max)
set @sql='select '
select @sql=@sql+'(select isnull('+name+','''') from T where id='+cast(column_id-1 as varchar(20))+
case when column_id=(select max(column_id) from sys.columns where object_id=object_id('T')) then ')' else ')+' end
from sys.columns where object_id=object_id('T') and column_id>1 order by column_id asc
exec(@sql)
----
34
--> 测试数据: #T
if object_id('tempdb.dbo.#T') is not null drop table #T
create table #T (id int identity, a int,b int,c int,d int)
insert into #T
select 1, 2, 3, 4 union all
select 5, 6, 7, 8 union all
select 9,10,11,12 union all
select 13,14,15,16
select sum(case id when 1 then a when 2 then b when 3 then c when 4 then d end) from #T