MySQL同桌计算错误的结果

时间:2013-08-24 19:14:42

标签: mysql

我正在尝试以下查询以进行计算/报告,但它给出了错误。

SELECT c.idx, c.club_name, s.sale_event_date, 
COUNT(s.*) AS total_guests, 
(SELECT COUNT(s.*) FROM sales s WHERE t2.qr_scanned = 1 AND t2.sale_event_date = s.sale_event_date) AS total_scanned_guests, 
SUM(s.rep_sale_commission) AS total_rep_commission, 
SUM(s.sale_commission) AS total_admin_fees
FROM club c
LEFT JOIN sales s ON s.club_id = c.idx
WHERE c.admin_id = 37
GROUP BY s.sale_event_date
ORDER BY sale_event_date DESC

错误是:

use near '*) AS total_guests, (SELECT COUNT(s.id) FROM sales s WHERE t2.qr_scanned = 1 AN' at line 2

2 个答案:

答案 0 :(得分:1)

您不在count(*)中包含表别名。

修复该问题后,您会发现子查询中存在别名问题。我认为子查询别名应该是t2而不是s

SELECT c.idx, c.club_name, s.sale_event_date, COUNT(*) AS total_guests, 
       (SELECT COUNT(*)
        FROM sales t2
        WHERE t2.qr_scanned = 1 AND t2.sale_event_date = s.sale_event_date
       ) AS total_scanned_guests, 
       SUM(s.rep_sale_commission) AS total_rep_commission, 
       SUM(s.sale_commission) AS total_admin_fees
FROM club c LEFT JOIN
     sales s ON s.club_id = c.idx
WHERE c.admin_id = 37
GROUP BY s.sale_event_date
ORDER BY sale_event_date DESC;

事实上,我认为你根本不需要子查询。看起来你只想要条件聚合:

SELECT c.idx, c.club_name, s.sale_event_date, COUNT(sales.club_id) AS total_guests, 
       sum(s.qr_scanned = 1) AS total_scanned_guests, 
       SUM(s.rep_sale_commission) AS total_rep_commission, 
       SUM(s.sale_commission) AS total_admin_fees
FROM club c LEFT JOIN
     sales s ON s.club_id = c.idx
WHERE c.admin_id = 37
GROUP BY s.sale_event_date
ORDER BY sale_event_date DESC;

答案 1 :(得分:0)

更改

COUNT(s*) AS total_guests

COUNT(*) AS total_guests

COUNT(s.id) AS total_guests

至少这似乎是你眼前的问题。