4

嘿,我正在使用 oracle sql 创建数据库。

我现在正在处理查询,我想出了两个单独的查询,我想合并它们以获得结果。

我创建的第一个查询是找出表演的总收入:

    SELECT SUM(bookings * CategoryPrice )AS Total_Money_Made
    FROM ( SELECT CategoryPrice , count(*) AS bookings
       FROM Booking b
       JOIN performance per
         ON b.performanceid =  per.performanceid
       JOIN Production p
         ON per.productionid = p.productionid          
      WHERE per.performanceid IN (1, 2, 3, 4)
      GROUP BY CategoryPrice)

这给了我一个结果:

TOTAL_MONEY_MADE

       337.5 

然后我有另一个查询,计算出总特许权:

              SELECT SUM(ConsessionAmount * 2) AS Total_Consession_Money
      FROM( SELECT COUNT (*) AS ConsessionAmount
FROM Booking 
WHERE 
Consession = 'Yes' AND PerformanceID = '1' OR 
Consession = 'Yes' AND PerformanceID = '2' OR 
Consession = 'Yes' AND PerformanceID = '3' OR 
Consession = 'Yes' AND PerformanceID = '4' )

这给了我以下结果:

TOTAL_CONSESSION_MONEY

                18 

现在我想要一种方法,可以从第一个查询中减去第二个查询的结果。是否可以?我该怎么做?我认为这与子查询有关,但我不太确定。

有什么帮助吗?谢谢。

4

3 回答 3

5

你可以这样做:

WITH TOTAL_MADE
AS
(   
    SELECT SUM(bookings * CategoryPrice )AS Total_Money_Made
    FROM ( SELECT CategoryPrice , count(*) AS bookings
       FROM Booking b
       JOIN performance per
         ON b.performanceid =  per.performanceid
       JOIN Production p
         ON per.productionid = p.productionid          
      WHERE per.performanceid IN (1, 2, 3, 4)
      GROUP BY CategoryPrice)
), TOTAL_CONSESSION
AS
(
    SELECT SUM(ConsessionAmount * 2) AS Total_Consession_Money
      FROM( SELECT COUNT (*) AS ConsessionAmount
    FROM Booking 
    WHERE 
    Consession = 'Yes' AND PerformanceID = '1' OR 
    Consession = 'Yes' AND PerformanceID = '2' OR 
    Consession = 'Yes' AND PerformanceID = '3' OR 
    Consession = 'Yes' AND PerformanceID = '4' )
)
SELECT
    TOTAL_CONSESSION.Total_Consession_Money-
    TOTAL_MADE.Total_Money_Made AS Something
FROM
    TOTAL_MADE,
    TOTAL_CONSESSION;
于 2012-05-08T08:18:32.230 回答
1

您可以使用括号在选择句子中使用选择

select (put your second query here) - (put your first select here) from dual
于 2012-05-08T08:19:26.163 回答
0

尝试类似:

SELECT Total_Money_Made - Total_Consession_Money FROM

( SELECT SUM(bookings * CategoryPrice )AS Total_Money_Made, ( SELECT SUM(ConsessionAmount * 2) AS Total_Consession_Money
      FROM( SELECT COUNT (*) AS ConsessionAmount
FROM Booking 
WHERE 
Consession = 'Yes' AND PerformanceID = '1' OR 
Consession = 'Yes' AND PerformanceID = '2' OR 
Consession = 'Yes' AND PerformanceID = '3' OR 
Consession = 'Yes' AND PerformanceID = '4' )
    FROM ( SELECT CategoryPrice , count(*) AS bookings
       FROM Booking b
       JOIN performance per
         ON b.performanceid =  per.performanceid
       JOIN Production p
         ON per.productionid = p.productionid          
      WHERE per.performanceid IN (1, 2, 3, 4)
      GROUP BY CategoryPrice) ) 
于 2012-05-08T08:18:53.860 回答