SQL query of Sum and Count from multiple tables

2019-08-15 21:56发布

I have the following two tables:

1. BList

  • BookingID
  • AdultNo
  • ChildNo
  • BookingDate

2. BHandle

  • BookingID
  • TicketingStatus
  • FinalSellingPrice
  • FinalNett
  • Staff

What I want to do is get the distinct Staff with Sum of (SellingPrice) , Sum of (NettPrice), Profit (Sum of sellingPrice)- Sum of (NettPrice)), No of Pax which is (AdultNo + ChildNo) and also count the BookingID as No of Bookings

WHERE BookingDate >= fromDate AND BookingDate <= toDate 
    AND TicketingStatus='CP'

Something that looks like this (The Total figures at the bottom doesn't matter as i will write them to csv format, i will handle the total there) but i need to figure out how to get the query first.

The list that i want to produce

This is the query i can get from the 2nd Table BHandle

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

This is my query for the 1st table BList

SELECT (adultno+childno) AS pax 
fFROM om BList
WHERE bookingdate >='01-mar-2013 00:00'
AND bookingdate <= '15-may-2013 23:59'

How can I combine these 2 queries together?

2条回答
再贱就再见
2楼-- · 2019-08-15 22:23

One way to do this is using union all with an aggregation:

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
查看更多
小情绪 Triste *
3楼-- · 2019-08-15 22:35

Something like this (assuming all columns are non null):

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;
查看更多
登录 后发表回答