2013-05-16 139 views
0

我有以下兩個表格SQL查詢,並從多個表計數

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)),其中的和平號是(AdultNo + ChildNo)也算BookingID爲無擔保

的WHERE BookingDate> = FROM日期和BookingDate < = TODATE AND TicketingStatus = 'CP'

的東西,看起來像這樣(在底部的總計數字沒有按」因爲我會將它們寫入csv格式,我將處理總數),但是我需要弄清楚如何首先獲取查詢。

The list that i want to produce

這是查詢我可以從第二個表得到BHandle

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

這是我的第一個表查詢BList

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

我有不知道如何將這兩個查詢結合在一起。

請幫忙。要做到這一點

回答

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; 
+0

謝謝。完美的作品 – ymcCole

0

一種方法是使用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 
+0

我沒有按公司有員工在BList表。給我一個錯誤'無效的列名員工' – ymcCole