Optimization
我應該避免重複引用視圖中的聚合列嗎?
所以我想總結一下我的業務應用程序中的賬戶餘額。我的(為我們的目的而簡化)數據模型如下所示:
--Main account table that holds the single accounts create table account ( id int primary key, descr varchar(50)) --This table holds the budgeted amount for the account. This table also holds the --'actual' adopted amount. The difference is that budgeted is what they thought it --should be, while adopted is what the board accepted. They can be different create table account_amount ( id int primary key, acct_id int foreign key references account (id), amount money, type tinyint) --Each monitary action against an account is contained here. This is the transactional --table create table account_journal ( id int primary key, acct_id int foreign key references account (id), amount money)
我想創建一個視圖來為我總結餘額,所以我有這樣的東西:
create view account_balance as select a.id, isnull(aaBudgeted.amount,0) as budgeted, isnull(aaAlloted.amount,0) as alloted , sum(isnull(aj.amount,0)) as journaled_activity, , isnull(aaAlloted.amount,0) + sum(isnull(aj.amount,0)) as balance from account a left join acct_amount aaBudgeted on a.id = aaBudgeted.acct_id and aaBudgeted.type = 2 left join acct_amount aaAlloted on a.id = aaAlloted.acct_id and aaAlloted.type = 1 and aaAlloted.is_current = 1 left join acct_journal aj on aj.acct_id = a.id where a.fiscal_year = 2012 group by a.id, aaBudgeted.amount, aaAlloted.amount
我的問題與:
isnull(aaAlloted.amount,0) + sum(isnull(aj.amount,0)) as balance
上面的線。我想像這樣引用聚合列兩次嗎?SQL Server 2k(不要讓我開始)是否足夠聰明,不會兩次將值相加?我有哪些選擇?
聚合只會計算一次,所以你沒問題。也就是說,我傾向於使用子查詢(根據@Aaron 的評論),但純粹是為了可讀性。