2014-06-20 88 views
0

不能找到任何地方這個問題......我有這樣的說法:SQL Server的ALTER TABLE與Case語句

select State=(CASE Discount 
WHEN 0 THEN sum((Price * Quantity) * (1 + Discount)) 
ELSE sum((Price * Quantity) * (Discount)) end) 
from Table1 where OrderID is not null group by Price, OrderID, Discount 
order by OrderID 

這是什麼東西做的是基礎計算是否有折扣列中的數字總計,原因是如果它的0,那麼我加1以防止總數被設置爲0,並且該數字將僅僅是自己的時間。另一個語句計算有百分比的餘數。現在,這個語句完美的作品,但我不能制定出在ALTER TABLE或UPDATE語句的順序/語法,任何幫助將是巨大的,歡呼:)這裏是我到目前爲止有:

Alter table Table1 add Total As 
(CASE Discount 
WHEN 0 THEN sum((Price * Quantity) * (1 + Discount)) 
ELSE sum((Price * Quantity) * (Discount)) end) 
from Table1 where OrderID is not null group by Price, OrderID, Discount  
order by OrderID 

^^上面不喜歡這個詞「從」

update Table1 Total = CASE Discount 
WHEN 0 THEN sum((Price * Quantity) * (1 + Discount)) 
ELSE sum(Price * Quantity) * (Discount)) end 

^^上面給出了這樣的錯誤 消息157,15級,狀態1,行 聚合不應出現在UPDATE語句的集合列表中。

+1

您不能在計算列中使用子查詢。如果你覺得這是一個定義,你需要重用,那麼你最好的選擇就是創建一個視圖。 – GarethD

+0

所以這是2以上錯誤意味着什麼呢? 加上,如果我創建一個視圖,我可以添加一個過程來更新視圖,以便總表自動更新?感謝您的幫助 – Crezzer7

+0

您不需要填充視圖,它基本上只是一個保存的查詢,所以當您引用視圖時,您將始終獲得最新結果。 – GarethD

回答

0

解決:

Create view ExtenededPriceView as: 
select OrderID, EquipmentID, ExtendedPrice = 
(Case 
WHEN 
(Discount = 0) THEN sum((UnitPrice * Quantity)) 
ELSE 
sum((1 - Discount) * UnitPrice) * Quantity END) 
from Table1 where OrderID is not null 
group by Discount, Quantity, EquipmentID, OrderID 

然後一個過程來調用:

create procedure UpdateExtendedPrice as 
update Table1 set Table1.ExtendedPrice = 
ExtenededPriceView.ExtendedPrice 
from Table1 inner join ExtenededPriceView on  
Table1.EquipmentID = ExtenededPriceView.EquipmentID 
where ExtenededPriceView.EquipmentID = 
(select TOP 1 EquipmentID from ExtenededPriceView order by EquipmentID desc) 
+0

'Case WHEN(Discount = 0)THEN sum((UnitPrice * Quantity)*(1 + Discount)' - 這沒有任何意義。 '表達式是檢查是否折扣爲0,那麼爲什麼要乘以1+折扣?只是不做任何乘法的所有特定條件。 – Ellesedil

+0

哈哈好點;)從來沒有想過一個通過 – Crezzer7

0

我真的不知道爲什麼你要了你的方式來創建一個視圖,然後程序,只是爲了更新一列。如果您要在整個代碼中反覆調用此代碼,則根據具體情況可能會有所幫助。但是如果你只是想在你的代碼中的一個地方引用這個,那麼就使用這個UPDATE。

http://sqlfiddle.com/#!6/486a9/2

--Setup 
CREATE TABLE Table1(
    ID INT, 
    Discount FLOAT, 
    Price FLOAT, 
    Quantity INT, 
    Total FLOAT 
); 

INSERT INTO Table1 (ID, Discount, Price, Quantity) VALUES (1, 0, 5, 5), (2, (1 - .15), 4.5, 3); 

--Doing work. 
UPDATE t SET Total = [State] 
FROM Table1 t, (select ID, [State]=(CASE Discount 
WHEN 0 THEN sum(Price * Quantity) 
ELSE sum(Price * Quantity * Discount) end) 
from Table1 GROUP BY ID, Discount, Price) a 
WHERE t.ID = a.ID; 

--See the results. 
SELECT * FROM Table1; 

這主要是數據庫就會怎樣對待你寫什麼,只是我沒有產生任何長期的數據庫對象,這一切簡化到一個查詢。我把你的SELECT清理了一下(現在少了很多括號)。我還假設你的ID列是唯一的。如果ID是唯一的,我認爲你不需要對價格進行GROUP。

但是,我認爲一個更好的解決方案是計算總數,或者在插入數據時或在需要數據時即時計算。