2016-08-15 85 views
-1

我有一个表中有4列,可能会定期添加或删除列。我需要一个动态查询,它可以在运行时处理列并执行计算。动态列col1 col2 col3 col3 col4

下面是我的表格以及记录样本的结构。

ID, col1,   col2,   col3,    col4 
1 '2016-08-09'  '2016-08-09' '2016-08-09'  '2016-08-09' 
2 '2016-08-10'  '2016-08-10' '2016-08-13'  '2016-08-04' 

我想结果,其中我的时间差应该来每列中,有一个应该总列应追加其给出特定的ID这些列的总数。结果集应如下所示。

ID col1 Col2 Col3 Col4 Total 
1 6  6  6 6  24 
2. 6  7  8 8  29 
+0

你如何获得的预期从采样数据输出...? – ZLK

+0

解释你的日期差分计算。 –

+0

您的ID日期差异看起来像是datediff(dd,coln,getdate()),但ID 2不遵循相同的模式 –

回答

1

经过测试,效果很好。 :)

--create table structure 
create table #test1 (ID int, col1 date, col2 date, col3 date, col4 date) 
go 

--insert sample data 
insert #test1 
select 1, '2016-08-09',  '2016-08-09', '2016-08-09',  '2016-08-09' 
union all 
select 2, '2016-08-10',  '2016-08-10', '2016-08-13',  '2016-08-04' 
union all 
select 3, '2016-08-10',  '2016-08-10', NULL,  '2016-08-04' 


--below is solution 
with cte_test1 (id, dif1, dif2, dif3, dif4) as 
(
    select id, 
      datediff(day, col1, getdate()) as dif1, 
      datediff(day, col2, getdate()) as dif2, 
      datediff(day, col3, getdate()) as dif3, 
      datediff(day, col4, getdate()) as dif4 
    from #test1 
) 
select id,dif1,dif2,dif3,dif4,ISNULL(dif1,0)+ISNULL(dif2,0)+ISNULL(dif3,0)+ISNULL(dif4,0) as difTotal 
from cte_test1 

结果:

enter image description here

+0

OP正在寻找动态 –

+0

感谢您指出。坦率地说,我不确定这里的“删除和添加列”是什么意思。我想通过删除列,OP意味着将其设置为空。 –

+0

你很可能是正确的。我的理解是列而不是行。也就是说,我有一个解决方案,但他从来没有回答我的问题。继续......欢呼声 –

相关问题