繁体   English   中英

SQL Server带有案例语句的变更表

[英]SQL Server Alter Table with Case Statement

在任何地方都找不到这个问题...我有这句话:

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表或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

上面的^^不喜欢单词“ FROM”

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

上面的^^给出此错误,消息157,级别15,状态1,行1聚合可能不会出现在UPDATE语句的设置列表中。

解决了:

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)

我不太确定为什么您会竭尽全力创建一个视图,然后创建一个过程,只是为了更新列。 如果要在整个代码中重复调用此函数,则视情况而定,这可能是有道理的。 但是,如果您只打算在代码中的某个位置引用它,那么,只需使用此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是唯一的,我认为您无需按价格分组。

但是,我认为,更好的解决方案是在对该数据进行INSERT或在需要数据时即时计算Total。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM