group by month and year, count from another table

前端 未结 3 2192
北海茫月
北海茫月 2021-01-26 11:23

im trying to get my query to group rows by month and year from the assignments table, and count the number of rows that has a certain value from the leads

3条回答
  •  无人共我
    2021-01-26 11:48

    This should do the trick:

    SELECT
    YEAR(FROM_UNIXTIME(a.date_assigned)) as d_year, 
    MONTHNAME(FROM_UNIXTIME(a.date_assigned)) as d_month,
    l.website,
    COUNT(*)
    FROM
    assignments AS a
    INNER JOIN leads AS l on (l.id = a.id_lead) /*are you sure, that you need a LEFT JOIN?*/
    WHERE id_dealership='$id_dealership2'
    GROUP BY
    d_year, d_month, website
    /*an ORDER BY is not necessary, MySQL does that automatically when grouping*/
    

    If you really need a LEFT JOIN, be aware that COUNT() ignores NULL values. If you want to count those as well (which I can't imagine to make sense) write it like this:

    SELECT
    YEAR(FROM_UNIXTIME(a.date_assigned)) as d_year, 
    MONTHNAME(FROM_UNIXTIME(a.date_assigned)) as d_month,
    l.website,
    COUNT(COALESCE(l.id, 1))
    FROM
    assignments AS a
    LEFT JOIN leads AS l on (l.id = a.id_lead)
    WHERE id_dealership='$id_dealership2'
    GROUP BY
    d_year, d_month, website
    

提交回复
热议问题