我被要求使用SQL中的视图生成数据集,并且有许多产品(例如' a'' b',&#39 ; c c')我希望计算总数超过5年(1,2,3,4,5)并输出总数为total_a_a_yr1,total_b_b_yr1 ....(见下面的代码)
有没有更有效的编码方式,而不是写出大量的代码行?
我考虑过创建一个程序,但我认为你不能在视图中使用EXEC。我可能错了。一个while循环可能是要走的路,但我不确定在视图中使用声明。
任何帮助将不胜感激。感谢
,sum(case when product = 'a a' and floor(datediff(dd, date1,date2)/365.25)<1
then amount_received else null end) as total_a_a_yr1
,sum(case when product = 'a a' and floor(datediff(dd, date1,date2)/365.25)<(2)
then amount_received else null end) as total_a_a_yr2
,sum(case when product = 'a a' and floor(datediff(dd, date1,date2)/365.25)<(3)
then amount_received else null end) as total_a_a_yr3
,sum(case when product = 'a a' and floor(datediff(dd, date1,date2)/365.25)<(4)
then amount_received else null end) as total_a_a_yr4
,sum(case when product = 'a a' and floor(datediff(dd, date1,date2/365.25)<(5)
then amount_received else null end) as total_a_a_yr5
答案 0 :(得分:0)
首先,case语句的默认值为NULL,因此&#34; ELSE NULL&#34;没有必要。其次,这个公式可能不完全符合您的想法:floor(datediff(dd, date1,date2)/365.25)
。我的意思是,如果您假设每四年有一个闰年,那么您就错了。闰年不会在被100整除的年份发生,除非它也可以除以400.但我可能误解了你想要做的事情。
您是正确的,您无法在视图中使用动态SQL(例如EXEC '<sql code>'
)。 对tally table的影响很小。以下是使用计数表以编程方式生成代码的方式(我将使用1到100):
with yourExpression(ex) as
(
select ',sum(case when product = ''''a a'''' and floor(datediff(dd, date1,date2)/365.25)<
then amount_received else null end) as total_a_a_yr'
),
iTally(N) as
(
select top(100) cast(row_number() over (order by (select null)) as varchar(3))
from sys.all_columns
)
select stuff(ex,78,0,'('+N+')')+N
from iTally
cross join yourExpression;
您可以按原样复制/粘贴并执行查询;它将返回:
,sum(case when product = ''a a'' and floor(datediff(dd, date1,date2)/365.25)<(1)
then amount_received else null end) as total_a_a_yr1
,sum(case when product = ''a a'' and floor(datediff(dd, date1,date2)/365.25)<(2)
then amount_received else null end) as total_a_a_yr2
,sum(case when product = ''a a'' and floor(datediff(dd, date1,date2)/365.25)<(3)....
--<truncated for brevity> ... as total_a_a_yr100