2014-12-19 62 views
0

我有2個表:客戶表和活動表。我試圖找出有多少客戶有2個具體的活動。例如,有多少客戶被購買併到達分行。 (我在活動錶行的一舉一動,客戶做到了。)這是查詢:在子查詢和主查詢日期之前

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

,但我需要知道買了多少後,他們arrvied,因爲有從網站上購買,比例在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 

,但其沒有工作..任何想法?

回答

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 
+0

謝謝!是工作! – 2014-12-19 16:22:27

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