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 ...這裏沒有魔法...... –