1
我有一个重复性的SQL查询来基于subaccounts/years,从subaccounts/years持有的金额列表中填充一个简单的表,但这里并没有一对一的关系。输出用于SSRS报告。简化重复的SQL Server查询
CREATE TABLE [dbo].[Results](
[SchemeDescription] [varchar](50) NULL,
[SubAccountYear] [varchar](15) NULL,
[RowNumber] [int] NULL,
[2008] [money] NULL,
[2009] [money] NULL,
[2010] [money] NULL,
[2011] [money] NULL,
[2012] [money] NULL,
[2013] [money] NULL,
[2014] [money] NULL,
[2015] [money] NULL,
[2016] [money] NULL,
[2017] [money] NULL,
[2018] [money] NULL,
[2019] [money] NULL,
[2020] [money] NULL,
[Processed] [int] NULL
) ON [PRIMARY]
UPDATE res
SET
[2008] = res.[2008] + isnull(x.[2008],0)
,[2009] = res.[2009] + isnull(x.[2009],0)
,[2010] = res.[2010] + isnull(x.[2010],0)
,[2011] = res.[2011] + isnull(x.[2011],0)
,[2012] = res.[2012] + isnull(x.[2012],0)
,[2013] = res.[2013] + isnull(x.[2013],0)
,[2014] = res.[2014] + isnull(x.[2014],0)
,[2015] = res.[2015] + isnull(x.[2015],0)
,[2016] = res.[2016] + isnull(x.[2016],0)
,[2017] = res.[2017] + isnull(x.[2017],0)
,[2018] = res.[2018] + isnull(x.[2018],0)
,[2019] = res.[2019] + isnull(x.[2019],0)
,[2020] = res.[2020] + isnull(x.[2020],0)
,processed = **1**
FROM [Results] res
INNER JOIN [Other_Income] as x
ON x.SubAccountYear = Cast(Cast(res.SubAccount AS Int)as Varchar(10)) + '¬'
+ Cast (YEAR(res.Inception_Date)+ **1** as varchar(4))
AND x.Processed = 0
WHERE res.RowNumber = 1
我必须重复10次以上的查询,以确保所有的子帐户年的分摊至适当的子帐户,由星号所包围的数字需要从1到枚举至10
I”我确定还有另外一种方法,但它没有解决。 任何想法赞赏。
感谢。我想知道我是否可以只使用SQL,而不是SP或循环。 – Anthony
存储过程*只是sql ...这里没有魔法...... –