简体   繁体   English

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

[英]SQL query of Sum and Count from multiple tables

I have the following two tables: 我有以下两个表:

1. BList 布鲁斯特

  • BookingID BookingID
  • AdultNo AdultNo
  • ChildNo ChildNo
  • BookingDate 预定日期

2. BHandle 2. BHandle

  • BookingID BookingID
  • TicketingStatus TicketingStatus
  • FinalSellingPrice FinalSellingPrice
  • FinalNett 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 我想要做的就是在distinct StaffSum of (SellingPrice) Sum of (NettPrice) Profit (Sum of sellingPrice)- Sum of (NettPrice)) ,没有和平的是(AdultNo + ChildNo)和另算预订BookingID为预订

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

我想要制作的清单

This is the query i can get from the 2nd Table BHandle 这是我可以从第2桌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 这是我对第一个表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? 如何将这两个查询组合在一起?

Something like this (assuming all columns are non null): 像这样(假设所有列都是非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;

One way to do this is using union all with an aggregation: 一种方法是使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM