仅在本月购买而不是在sql之前购买的客户

时间:2016-10-07 19:01:52

标签: mysql sql select count

我有一份购买记录清单,需要知道当月购买的用户总数,但过去几个月从未购买过 date_buy =购买日期

$hoy = date("Y-m-d");
$mesActual = date("Y-m-01");

SELECT count(DISTINCT(id_user)) 
        FROM transaction
        where date_buy BETWEEN '$mesActual' and '$hoy'
        AND date_buy >(select min(date_buy) FROM transaction)

感谢

2 个答案:

答案 0 :(得分:1)

可能的方法是

 SELECT count(DISTINCT(id_user)) 
 FROM transaction t1
 WHERE date_buy BETWEEN '$mesActual' and '$hoy'
    AND NOT EXISTS (SELECT 1 FROM transaction t2 WHERE t2.id_user = t1.id_user AND t2.date_buy < '$mesActual')

答案 1 :(得分:0)

找出在日期之前购买的用户,然后根据他们的id_users&#39;

进行限制
    SELECT count(DISTINCT(id_user)) 
    FROM transaction
    where date_buy BETWEEN '$mesActual' and '$hoy'
    AND id_user NOT IN (select id_user FROM transaction where date_buy < '$mesActual')