Multiple counts within a single SQL query

前端 未结 2 633
日久生厌
日久生厌 2020-12-28 09:10

I\'m trying to get the count of documents within 4 specific sections using the following code:

SELECT
    category.id
    , category.title
    , count(ts1.se         


        
2条回答
  •  眼角桃花
    2020-12-28 09:50

    You might want to try something like this:

    SELECT
        category.id
        , category.title
        , SUM(IF(ts1.section_id = 1, 1, 0)) AS doc1
        , SUM(IF(ts1.section_id = 2, 1, 0)) AS doc2
        , SUM(IF(ts1.section_id = 3, 1, 0)) AS doc3
        , SUM(IF(ts1.section_id = 4, 1, 0)) AS doc4
    FROM
        category 
        LEFT JOIN category_link_section AS ts1
            ON (category.id = ts1.category_id AND ts1.section_id = 1)
    GROUP BY category.id, ts1.section_id
    

提交回复
热议问题