我已经计算了不同表中计数的总和。重复两次,每个performanceID一次。现在,我想获得两个和的和。

以下是我目前所做的两个和的代码:

    SELECT SUM((COUNT (BookingID) * CategoryPrice)) AS TotalAmount
    FROM Booking, Production
    WHERE Booking.PerformanceID IN(SELECT PerformanceID FROM Performance WHERE PerformanceID = '1')
    and Production.ProductionID IN
    (SELECT ProductionID FROM Performance WHERE PerformanceID = '1')
    GROUP BY BookingID, CategoryPrice
    UNION ALL
    SELECT SUM((COUNT (BookingID) * CategoryPrice)) AS TotalAmount
    FROM Booking, Production
    WHERE Booking.PerformanceID IN(SELECT PerformanceID FROM Performance WHERE PerformanceID = '2')
    and Production.ProductionID IN
    (SELECT ProductionID FROM Performance WHERE PerformanceID = '2')
     GROUP BY BookingID, CategoryPrice


我得到的结果是:

总金额
-----------
70
60


我如何在这里总结两个总和?

最佳答案

我永远都不会与FGITW竞争,但是我不得不对这个查询说点什么...
如果我们添加空格,希望您能明白我的意思:

SELECT SUM( (COUNT(BookingID) * CategoryPrice) ) AS TotalAmount
  FROM Booking
     , Production
 WHERE Booking.PerformanceID IN ( SELECT PerformanceID
                                   FROM Performance
                                  WHERE PerformanceID = '1')
   AND Production.ProductionID IN ( SELECT ProductionID FROM Performance
                                     WHERE PerformanceID = '1')
 GROUP BY BookingID, CategoryPrice
 UNION ALL
SELECT SUM( (COUNT(BookingID) * CategoryPrice)) AS TotalAmount
  FROM Booking
     , Production
 WHERE Booking.PerformanceID IN ( SELECT PerformanceID
                                    FROM Performance
                                   WHERE PerformanceID = '2')
   AND Production.ProductionID IN ( SELECT ProductionID
                                      FROM Performance
                                     WHERE PerformanceID = '2')
 GROUP BY BookingID, CategoryPrice

将查询分解为返回两行的唯一原因是解析函数和全部并集。

您正在bookingproduction之间进行cartesian join,这意味着您将彼此之间的行数相乘。
您在performance上的子选择将返回一个已知的值。根本没有理由这样做。
您正在将数字隐式转换为字符串,然后再次转换为数字。
您在这里扫描表或索引8次!

似乎您希望获得每种性能的总费用,在这种情况下,您的查询可以简化为以下内容:
SELECT SUM(bookings * CategoryPrice)
  FROM ( SELECT CategoryPrice , count(*) as bookings
           FROM Booking b
           JOIN performance per
             ON p.performanceid =  per.performanceid
           JOIN Production p
             ON p.productionid = per.productionid
          WHERE p.performanceid in (1, 2)
          GROUP BY CategoryPrice
                )

请注意显式连接语法,这种语法已经存在了几十年,使事情变得更加清晰和helps stop mistakes。假设您在两个表的booking上都有索引,此查询将执行两次范围扫描,production之一和performanceid之一。假设performance是该表的主键,它还将对performanceid进行唯一扫描。
作为对此功能的解释,现在我终于设法使您的模式正确!我们选择两个表演12。然后,我们选择与这些表演相关的每个作品以及与这些表演相关的每个预订。您可能可以根据categoryprice的表来进一步简化此操作。然后,我们得到每个categoryprice的预订数量,并对这些产品的乘积求和以得出总价值。
作为一点建议,我总是建议您在接受查询正确之前,先了解要从查询返回的值。最好的人会犯错误。因为您可以看到返回的值不正确而能够捕获它们,这将有所帮助。
进一步阅读:

Join (SQL)-维基百科
A Visual Explanation of SQL Joins-编码恐怖
In Function-网上技术

10-08 16:16