在子查询和主查询之前的日期

时间:2014-12-19 07:21:18

标签: php mysql sql

我有2个表:客户表和活动表。我试图找到有多少客户有2个特定的活动。例如,有多少客户被买入并到达分行。 (我在活动表中列出了客户所做的每一个行为。)这是查询:

SELECT COUNT(*) as total FROM activity
WHERE activity = 'arrived' AND
customerid IN
(SELECT DISTINCT(customerid) FROM activity
WHERE activity = 'bought')

但是我需要知道在他们购买之后买了多少,因为有客户从网站上购买,而不是在1年后到达分店。所以我只想要到达而不是买的顾客。 我试过这个:

SELECT COUNT(*) as total, daten as odaten FROM activity
WHERE activity = 'arrived' AND
customerid IN
(SELECT DISTINCT(customerid), daten as tdaten FROM activity
WHERE activity = 'bought') HAVING odaten < tdaten

但它没有用......有什么想法吗?

2 个答案:

答案 0 :(得分:0)

你的方向错误。您不应该使用子查询。相反,你应该尝试自我加入。这是我的解决方案:

--activity customerid daten
select count(customerid) as finalcount from(
select distinct t1.customerid
from tablename t1
inner join tablename t2 on t1.customerid=t2.customerid
where t1.activity='arrivived' and t2.activity='bought' and t1.daten<t2.daten
)t

答案 1 :(得分:0)

你可以试试这样的事情

SELECT COUNT(a.*) 
FROM activity a
INNER JOIN 
 (SELECT customerid, MAX(daten) as BoughtDate
  FROM activity
  WHERE activity = 'bought'
  GROUP BY customerid) t
ON a.customerid = t.customerid
WHERE a.activity = 'arrived'
  AND a.daten < t.BoughtDate