【问题标题】:How can I subtract two queries in sql?如何在sql中减去两个查询?
【发布时间】:2015-11-18 06:10:04
【问题描述】:

我的第一个查询返回值 20:

    SELECT numberofseats
    from plane
    where tail number in
     ( select flighttailnumberfk
       from flight
       where departuretime between '11/29/2014' and '11/30/2014' and
             flightdepartureairportfk = 'jfk' and
             flightarrivalairport = 'mli'
     )

我的第二个查询返回 1:

    select count(reservationseatfk)
    from flight f, reservation r
    where f.departuretime between '11/29/2014' and '11/30/2014' and
          f.reservationflightidfk = f.flightid and r.reservationdeparturetimefk = f.departuretime

现在我的问题是我想从第二个查询中减去第一个查询并给我答案 19。我该怎么做?

【问题讨论】:

  • 您使用的是哪个 DBMS? '11/29/2014' 不是(标准)SQL 中的有效日期文字

标签: sql database


【解决方案1】:

你可以使用 sub sql 来减去

SELECT numberofseats - ( select count(reservationseatfk)
    from flight f, reservation r
    where f.departuretime between '11/29/2014' and '11/30/2014' and
          f.reservationflightidfk = f.flightid and r.reservationdeparturetimefk = f.departuretime)
    from plane
    where tail number in
     ( select flighttailnumberfk
       from flight
       where departuretime between '11/29/2014' and '11/30/2014' and
             flightdepartureairportfk = 'jfk' and
             flightarrivalairport = 'mli'
     )

【讨论】:

  • 这对我来说完美无缺!但是介意我问一个问题吗?这与执行 select (query1) - (query2) 有何不同?因为我之前做过,但对我没有用。
  • 您只能使用一个 select 语句(除了 union,减号)。如果你想使用加、减、除等运算符,你需要一个变量。通过子选择,你得到你想要使用的变量。
【解决方案2】:

你可以通过以下方式做到这一点:

SELECT (query1) - (query2)

SELECT (query1)  - (query2) AS Difference

select @result = (query1) - (query2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 2019-09-18
    • 2023-01-15
    • 2019-11-20
    • 1970-01-01
    相关资源
    最近更新 更多