SQL query of Sum and Count from multiple tables

荒凉一梦 提交于 2019-12-24 16:26:00

问题


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.

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?


回答1:


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;



回答2:


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


来源:https://stackoverflow.com/questions/16577845/sql-query-of-sum-and-count-from-multiple-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!