简体   繁体   中英

MySQL pivot with multiple counts

This is a snapshot of my MySQL table:

在此输入图像描述

Is it possible to write a query to get such a pivot table like output...

在此输入图像描述

How about something like

SELECT url_host,
    SUM(CASE WHEN post_id = -1 THEN 1 ELSE 0 END) as post_id_minus1,
    SUM(CASE WHEN post_id = 0 THEN 1 ELSE 0 END) as post_id_0,
    etc...
FROM    YOUR_TABLE
GROUP BY url_host

You can use CASE statement on this to pivot your table.

SELECT  url_host,
        COUNT(CASE WHEN post_ID = -1 THEN 1 ELSE NULL END) Negative_One,
        COUNT(CASE WHEN post_ID = 0 THEN 1 ELSE NULL END) Zero,
        COUNT(CASE WHEN post_ID > 0 THEN 1 ELSE NULL END) Greater_Zero
FROM tableName
GROUP BY url_host

SQLFiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM