sql >> Database teknologi >  >> RDS >> Mysql

Avancerede sum-aggregerede felter

Skriv underforespørgsler for at få samlet klik og salg for hver annonce i datointervallet. Slut dig til disse med ad tabel for at få annoncenavnet og product tabel for at få produktnavnene. Kombiner produktnavnene ved hjælp af GROUP_CONCAT .

SELECT ad.ad_name, IFNULL(clicks, 0) AS clicks, IFNULL(product_sale, 0) AS product_sale, IFNULL(GROUP_CONCAT(DISTINCT p.product_name), '') AS products
FROM ad
LEFT JOIN (
    SELECT ad_id, SUM(clicks) AS clicks
    FROM ad_insight
    WHERE date BETWEEN '2021-04-23' AND '2021-04-25'
    GROUP BY ad_id
) AS ai ON ai.ad_id = ad.ad_id
LEFT JOIN (
    SELECT ad_id, SUM(sale) AS product_sale
    FROM ads_products AS ap
    LEFT JOIN product_insight AS pi ON pi.product_id = ap.product_id
    WHERE date BETWEEN '2021-04-23' AND '2021-04-25'
    GROUP BY ad_id
) AS pi ON pi.ad_id = ad.ad_id
LEFT JOIN ads_products AS ap ON ap.ad_id = ad.ad_id
LEFT JOIN product AS p ON ap.product_id = p.product_id
GROUP BY ad.ad_id

DEMO




  1. Advarsel:mysql_query() forventer, at parameter 2 er ressource, boolesk givet i C:\wamp\www\pyrll\emlhome.php på linje 15

  2. Fejlfinding af SQL Server-replikering

  3. Objektet 'DF__*' er afhængig af kolonne '*' - Ændring af int til dobbelt

  4. MySQL LEFT JOIN med GROUP BY og WHERE IN (underforespørgsel)