MySQL LEFT JOIN with GROUP BY and WHERE IN (sub query)

前端 未结 1 578
-上瘾入骨i
-上瘾入骨i 2021-02-13 17:55

I have one table with some statistics per date, which I want listed out with MySQL. For some dates there will be no statistics, so the result should look something like this:

相关标签:
1条回答
  • 2021-02-13 18:03
    SELECT  a.date, COUNT(b.campaignid) totalStat
    FROM    campaigndata a
            LEFT JOIN campaignfilter b
                ON  a.campaignid = b.campaignid AND
                    b.campaigntype = 1
    GROUP   BY a.date
    

    To further gain more knowledge about joins, kindly visit the link below:

    • Visual Representation of SQL Joins

    UPDATE 1

    SELECT  a.date, 
            COALESCE(b.totals,0) totals
    FROM    demo_calendar a
            LEFT JOIN
            (
                SELECT  a.date, SUM(impressions) totals
                FROM    demo_campaigndata a
                        INNER JOIN demo_campaignfilter b
                            ON a.campaignid = b.campaignid
                WHERE   b.campaigntype = 1
                GROUP   BY a.date
            ) b ON a.date = b.date
    
    • SQLFiddle Demo
    0 讨论(0)
提交回复
热议问题