SQL:在COUNT列上进行数学运算

时间:2017-03-29 05:12:08

标签: mysql sql count group-by

SELECT January.customer_id AS Jancust_id, 
COUNT( DISTINCT January.customer_id ) AS Jan_orig_cust,
COUNT (DISTINCT payments.customer_id) as Jan_retain_cust,
Jan_retain_cust/ 1533 AS CAC_referral
FROM January_Cohort January
LEFT JOIN telemon_payments_data payments
ON January.customer_id = payments.customer_id
WHERE January.acquisition_source = 'referral'
AND 
payments.payment_date BETWEEN '2016-06-01' and '2016-06-31'

好的,我不能对使用COUNT&的同一查询中的列进行数学运算。刚刚结束?错误信息如下。

  

“#1064 - 您的SQL语法出错;请查看手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近'DISTINCT payments.customer_id)的Jan_retain_cust,   Jan_retain_cust / 1533 AS CAC_'在第3行“

2 个答案:

答案 0 :(得分:0)

您缺少group by条款。此外,您尝试在 not 允许的同一选择中的表达式中使用别名Jan_retain_cust。只需使用原始表达式Jan_retain_cust替换别名COUNT (DISTINCT payments.customer_id)

select January.customer_id as Jancust_id,
    COUNT(distinct January.customer_id) as Jan_orig_cust,
    COUNT(distinct payments.customer_id) as Jan_retain_cust,
    COUNT(distinct payments.customer_id) / 1533 as CAC_referral
from January_Cohort January
left join telemon_payments_data payments on January.customer_id = payments.customer_id
where January.acquisition_source = 'referral'
    and payments.payment_date between '2016-06-01' and '2016-06-31'
group by January.customer_id;

答案 1 :(得分:0)

不能在同一查询中引用别名列。

SELECT January.customer_id AS Jancust_id, 
COUNT( DISTINCT January.customer_id ) AS Jan_orig_cust,
COUNT (DISTINCT payments.customer_id) as Jan_retain_cust,
Jan_retain_cust/ 1533 AS CAC_referral    <--- You can not do.
FROM January_Cohort January
LEFT JOIN telemon_payments_data payments
ON January.customer_id = payments.customer_id
WHERE January.acquisition_source = 'referral'
AND 
payments.payment_date BETWEEN '2016-06-01' and '2016-06-31'

另外,正如@GurV指出的那样,你也缺少group by条款。