[英]How Can i subtract two columns in different tables in SQL
I want to enter in a query the subtract between two columns in different tables it keeps saying error ... 我想在查询中输入不同表中两列之间的减法,并一直说错误...
SELECT FlightDate,
Plane,
Destination,
Capacity
FROM
FlightSchedule,
Routes,
Aircrafts
WHERE
FlightSchedule.RID=Routes.RouteID
AND FlightSchedule.Plane=Aircrafts.AcID
AND (SELECT SUM(Capacity)
FROM Aircrafts)
-
(SELECT Class , count(*)
FROM Tickets);
The query is wrong on multiple levels. 该查询在多个级别上是错误的。
First of all, you cannot put the details of SELECT capacity as a sub query under WHERE. 首先,您不能将SELECT容量的详细信息作为子查询放在WHERE下。 The WHERE clause is for conditional parameters.
WHERE子句用于条件参数。
Try this: 尝试这个:
WITH VACANCY as (SELECT SUM(Capacity) FROM Aircrafts) - (SELECT Count(*) FROM Tickets)
SELECT FlightDate,Plane, Destination, Vacancy
FROM FlightSchedule,Routes,Aircrafts
WHERE FlightSchedule.RID=Routes.RouteID AND FlightSchedule.Plane=Aircrafts.AcID;
You also need to a condition for the select count for tickets but I don't know the schema of tickets so... 您还需要为票证的选择计数设置一个条件,但我不知道票证的架构,所以...
I would split this up into 2 parts. 我将其分为两部分。 First get the data you need, then perform the math.
首先获取所需的数据,然后执行数学运算。 You are also using old SQL syntax.
您还使用了旧的SQL语法。 You should re-format using the new JOIN syntax.
您应该使用新的JOIN语法重新设置格式。 It's also easier to read.
它也更容易阅读。
1st declare a table to hold you flight schedule and aircraft info. 1号声明一张表格,以保存您的航班时刻表和飞机信息。
Declare @AIRCRAFTCAPACITY Table
(
[FlightDate] [datetime] NOT NULL,
[Plane] [varchar](50) NOT NULL,
[Destination] [varchar](50) NOT NULL,
[Capacity] [INT] NOT NULL,
[NoOfSeatsRemaining] [INT] NULL
);
Then insert the data you need. 然后插入所需的数据。
INSERT @AIRCRAFTCAPACITY
(
[FlightDate],
[Plane],
[Destination],
[Capacity]
)
SELECT FS.FlightDate,
A.Plane,
FS.Destination,
A.Capacity
FROM
FlightSchedule FS
INNER
JOIN Routes R
ON
FS.RID = R.RouteID
INNER
JOIN Aircrafts A
ON
FS.Plane = A.AcID
Now perform the math to calculate the remaining capacity. 现在执行数学计算剩余容量。 I've made an assumption that you are doing this for a particular route.
我已经假设您正在针对特定路线进行此操作。 But I'm sure you can adjust your SQL accordingly.
但是我确定您可以相应地调整SQL。
UPDATE @AIRCRAFTCAPACITY
SET
[NoOfSeatsRemaining] = [Capacity] - T.TICKETS_SOLD
FROM
@AIRCRAFTCAPACITY A
INNER
JOIN
(
SELECT ROUTEID, COUNT(ROUTEID) AS TICKETS_SOLD
FROM
Tickets T1
WHERE
T1.ROUTEID = A.ROUTEID
GROUP
BY ROUTEID
) T
ON
A.ROUTEID = T.ROUTEID
Apolgies if the syntax is a little off as it's hard to construct SQL when you dont have the underlying tables. 如果语法略有偏差,请使用Apolgie,因为在没有基础表时很难构造SQL。
But hopefully it will help. 但希望它将有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.