如何获得Campaing_ids的前10名记录?

时间:2014-05-26 16:15:01

标签: mysql sql database greatest-n-per-group

我希望每个广告系列的前10个记录并尝试下面但是它给了我Campaing_id = 1的前20个记录。

如何获取每个caimpaingn前10条记录的记录。我在下面的查询中尝试过。

SELECT CG.*, COUNT(*) AS ageCount, DATEDIFF( NOW(), CG.domain_creation_date ) AS age, CASE
                    WHEN DATEDIFF( NOW(), CG.domain_creation_date ) >= 365 THEN 'old' 
                    WHEN (DATEDIFF(NOW(), CG.domain_creation_date) < 365 AND DATEDIFF(NOW(), CG.domain_creation_date) > 180) THEN 'young'
                    WHEN DATEDIFF(NOW(), CG.domain_creation_date) <= 180 THEN 'new'
                    END AS ageType,
                    CG.date_added
                    FROM serp_google_crawl_data AS CG
                    WHERE CG.date_added = '2014-05-26'  AND CG.campaign_id IN (1,2)  GROUP BY CG.rank ORDER BY CG.rank, CG.id LIMIT 0, 20

我正在使用mysql。感谢。

1 个答案:

答案 0 :(得分:0)

这就是我的意思:

SELECT CG.*, COUNT(*) AS ageCount, DATEDIFF( NOW(), CG.domain_creation_date ) AS age,
    'new' ageType,  CG.date_added
    FROM serp_google_crawl_data AS CG
    WHERE CG.date_added = '2014-05-26'  AND CG.campaign_id IN (1,2)  
    AND DATEDIFF(NOW(), CG.domain_creation_date) <= 180
    GROUP BY CG.rank ORDER BY CG.rank, CG.id LIMIT 0, 10

UNION

SELECT CG.*, COUNT(*) AS ageCount, DATEDIFF( NOW(), CG.domain_creation_date ) AS age,
    'young' ageType,    CG.date_added
    FROM serp_google_crawl_data AS CG
    WHERE CG.date_added = '2014-05-26'  AND CG.campaign_id IN (1,2)  
    AND (DATEDIFF(NOW(), CG.domain_creation_date) BETWEEN 364 AND 179) 
    GROUP BY CG.rank ORDER BY CG.rank, CG.id LIMIT 0, 10                    

UNION

SELECT CG.*, COUNT(*) AS ageCount, DATEDIFF( NOW(), CG.domain_creation_date ) AS age,
    'old' ageType,  CG.date_added
    FROM serp_google_crawl_data AS CG
    WHERE CG.date_added = '2014-05-26'  AND CG.campaign_id IN (1,2)  
    AND  DATEDIFF( NOW(), CG.domain_creation_date ) >= 365
    GROUP BY CG.rank ORDER BY CG.rank, CG.id LIMIT 0, 10