[英]Adding a calculated column using different table SQL
I'm new to SQL so please bare with.我是 SQL 的新手,所以请放心。
I am trying to add a calculated column called 'InvoiceAmount' to my 'CompanyInvoice' table.我正在尝试将一个名为“InvoiceAmount”的计算列添加到我的“CompanyInvoice”表中。
My CompanyInvoice table currently has the following columns:我的 CompanyInvoice 表当前具有以下列:
CREATE TABLE CompanyInvoice(
InvoiceID CHAR(5) NOT NULL,
CompanyAccountID CHAR(5) NOT NULL CONSTRAINT FK_CompanyInvoice_CompanyAccount
FOREIGN KEY REFERENCES CompanyAccount(CompanyAccountID) ON UPDATE CASCADE,
CompanyID CHAR(5) NOT NULL CONSTRAINT FK_CompanyInvoice_ProductionCompany
FOREIGN KEY REFERENCES ProductionCompany(CompanyID),
BookingID CHAR(5) NOT NULL CONSTRAINT FK_CompanyInvoice_EventBooking
FOREIGN KEY REFERENCES EventBooking (BookingID),
TheatreID CHAR(5) NOT NULL CONSTRAINT FK_CompanyInvoice_Theatre
FOREIGN KEY REFERENCES Theatre(TheatreID)ON UPDATE CASCADE);
I would like to add a new column which calculates the invoice amount - invoice amount is calculated dependant on duration of event (EventDuration column is held in a different 'Event' table) and the 'TheatreID' for example if TheatreID=1 then EventDuration x 300, if TheatreID=2 then EventDuration x 1000.我想添加一个计算发票金额的新列 - 发票金额的计算取决于事件的持续时间(EventDuration 列保存在不同的“事件”表中)和“TheatreID”,例如如果 TheatreID=1 则 EventDuration x 300,如果 TheatreID=2 则 EventDuration x 1000。
Many Thanks非常感谢
A view, as you described, would look like正如您所描述的,一个视图看起来像
create view v_invoice as
select c.InvoiceID,
e.EventDuration * case when c.TheatreID = 1 then 300
when c.TheatreID = 2 then 1000
end as invoice_amount
from CompanyInvoice c join ... ??? unknown; how to get to Event table?
As you can see, ???
如你所见, ???
means that you didn't describe how to get from data we know to Event
table.意味着您没有描述如何从我们知道的数据中获取Event
表。
On the other hand, it is probably not a very good idea to multiply anything with hardcoded values ( 300
, 1000
) because - what if they change?另一方面,将任何东西与硬编码值( 300
、 1000
)相乘可能不是一个好主意,因为 - 如果它们改变了怎么办? Will you modify all code you write to implement those changes?您会修改您编写的所有代码以实现这些更改吗? From what you said so far, those should be another column in Theatre
table (or a new table, if you want to track changes over time; that new table would be in parent-child relationship with Theatre
).从你到目前为止所说的,那些应该是Theatre
表中的另一列(或者一个新表,如果你想跟踪随时间的变化;那个新表将与Theatre
处于父子关系)。
Something like this (note that I'm still guessing join conditions):像这样的东西(请注意,我仍在猜测加入条件):
create view v_invoice as
select c.InvoiceID,
e.EventDuration * t.value as invoice_amount
-------
this, instead of hardcoded 300 or 1000 or ...
from CompanyInvoice c join Theatre t on t.TheatreID = c.TheatreID
join Event e on e.EventID = t.EventID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.