从多个表中查询Sum和Count的SQL

时间:2013-05-16 01:59:40

标签: sql count sum multiple-tables

我有以下两个表:

1。 BList

  • BookingID
  • AdultNo
  • ChildNo
  • BookingDate

2。 BHandle

  • BookingID
  • TicketingStatus
  • FinalSellingPrice
  • FinalNett
  • 员工

我想要做的是distinct StaffSum of (SellingPrice)Sum of (NettPrice)Profit (Sum of sellingPrice)- Sum of (NettPrice)),Pax的(AdultNo + ChildNo),并计算{ {1}}为No of Bookings

BookingID

看起来像这样的东西(底部的总数不重要,因为我会将它们写成csv格式,我将处理总数)但我需要弄清楚如何首先获得查询。

The list that i want to produce

这是我可以从第二张表 BHandle

获得的查询
WHERE BookingDate >= fromDate AND BookingDate <= toDate 
    AND TicketingStatus='CP'

这是我对第一张表 BList

的查询
SELECT Staff, SUM(FinalSellingPrice) AS gross, SUM(FinalNett) AS cost
FROM BHandle
WHERE ticketingstatus ='CP'
GROUP BY Staff

如何将这两个查询组合在一起?

2 个答案:

答案 0 :(得分:3)

这样的事情(假设所有列都是非空的):

select Staff,
    sum(FinalSellingPrice) as gross,
    sum(FinalNett) as cost,
    sum(FinalSellingPrice - FinalNett) as profit,
    sum(AdultNo+ChildNo) as pax,
    count(1) as bookings
from Blist b
inner join BHandle bh on b.BookingID = bh.BookingID
where b.BookingDate >= fromDate
    and b.BookingDate <= toDate
    and bh.TicketingStatus = 'CP'
group by staff;

答案 1 :(得分:1)

执行此操作的一种方法是将union all与聚合一起使用:

select staff, sum(gross) as gross, sum(cost) as cost, sum(pax) as pax,
       sum(numbookings) as numbookings
from ((SELECT Staff, SUM(FinalSellingPrice) AS gross, SUM(FinalNett) AS cost,
              null as pax, null as numbookings
       FROM BHandle
       WHERE ticketingstatus ='CP'
       GROUP BY Staff
      ) union all
      (select staff, null as gross, null as cost, (adultno+childno) AS pax ,
              count(*) as numbookings
       from blist join
            bhandle
            on blist.bookingid = bhandle.bookingid
       group by staff
      )
     ) t
group by staff