【发布时间】:2018-06-20 03:42:30
【问题描述】:
我被要求使用 SQL 中的视图生成数据集,并拥有许多产品(例如“a a”、“b b”、“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
【问题讨论】:
-
微软 SQL 服务器
-
我不知道投反对票的目的是什么——这是个好问题。对我的问题投赞成票。
标签: sql sql-server tsql view while-loop