Mysql

在 SELECT 子句中使用 SUM 計算門票銷售額

  • August 15, 2018

dbfiddle上的票務設置中,我試圖通過將票價乘以該事件的售票總數,根據其類型(即標準 VIP)來計算特定事件的售票量。

到目前為止,我有這個查詢,

SELECT tt.ticket_type,COUNT(tt.ticket_type) AS 'tickets_paid' , SUM((COUNT(tt.ticket_type)) *tc.price) 
FROM tbl_tickets t INNER JOIN tbl_ticket_count tc ON t.ticket_count_id = tc.ticket_count_id 
INNER JOIN tbl_events_new e ON tc.event_id = e.event_id 
INNER JOIN tbl_ticket_type tt ON tt.ticket_type_id = tc.ticket_type_id
WHERE e.event_id = 164 AND t.pay_status ='paid' GROUP BY tt.ticket_type

但是在添加子句的乘法部分後,我不斷收到“組函式的無效使用 - 1111”錯誤。如何使用 SUM 函式使用小數類型的票價和售出的票數執行此操作?

在對上一個答案進行了幾個小時的測試後,我決定刪除子查詢,因為它在集合中產生重複的結果,並簡單地從COUNT票證總數中相乘,如下所示:

SELECT tt.ticket_type,tc.price,
       COUNT(tt.ticket_type_id) AS tickets_paid_count ,(COUNT(tt.ticket_type_id) * tc.price) AS tickets_paid_sales
FROM tbl_tickets t 
   INNER JOIN tbl_ticket_count tc ON t.ticket_count_id = tc.ticket_count_id
   INNER JOIN tbl_events_new e ON tc.event_id = e.event_id 
   INNER JOIN tbl_ticket_type tt ON tt.ticket_type_id = tc.ticket_type_id
WHERE 
   e.event_id = '$eid' AND t.pay_status ='paid' 
GROUP BY tt.ticket_type,tc.price

變數$eid傳遞給 PHP 腳本的位置。

試試這個:

SELECT 
A.ticket_type_id, 
A.tickets_paid, 
A.tickets_paid*B.price as amount_paid
FROM
(SELECT tt.ticket_type_id,
COUNT(tt.ticket_type_id) AS tickets_paid 
FROM tbl_tickets t 
   INNER JOIN tbl_ticket_count tc 
       ON t.ticket_count_id = tc.ticket_count_id 
   INNER JOIN tbl_events_new e 
       ON tc.event_id = e.event_id 
   INNER JOIN tbl_ticket_type tt ON 
       tt.ticket_type_id = tc.ticket_type_id
WHERE 
   e.event_id = 164 
   AND t.pay_status ='paid' 
GROUP BY tt.ticket_type_id) as A
INNER JOIN tbl_ticket_count B ON 
       A.ticket_type_id = B.ticket_type_id

引用自:https://dba.stackexchange.com/questions/214929