【问题标题】:SQL server View - loop help (while loop)SQL server 查看 - 循环帮助(while 循环)
【发布时间】: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


【解决方案1】:

首先,case 语句的默认值为 NULL,因此“ELSE NULL”不是必需的。其次,这个公式可能并不完全符合您的想法:floor(datediff(dd, date1,date2)/365.25)。我的意思是,如果你假设每四年有一个闰年,那你就错了。闰年不会发生在可以被 100 整除的年份,除非它也可以被 400 整除。不过,我可能会误解你想要做什么。

你是对的,你不能在视图中使用动态 SQL(例如EXEC '&lt;sql code&gt;')。使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 2020-03-01
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 2010-11-21
    相关资源
    最近更新 更多