简体   繁体   中英

Php Mysql Multiple Group By Results in Single Line

I have data structure Below在此处输入图像描述

I need results with group by country and group by count results like below在此处输入图像描述

I have tried below code it is

$sql = "SELECT Country, 
     (SELECT COUNT(*) FROM   ip_ptc WHERE type='view' and ad_id=" . $db->real_escape_string($input->gc['aid']) .") as view,
     (SELECT COUNT(*) FROM   ip_ptc WHERE type='interactions' and ad_id=" . $db->real_escape_string($input->gc['aid']) .") as interactions,
     (SELECT COUNT(*) FROM   ip_ptc WHERE type='click' and ad_id=" . $db->real_escape_string($input->gc['aid']) .") as click,
        ROUND(100.0*COUNT(ip)/(SELECT COUNT(*) FROM ip_ptc WHERE ad_id=" . $db->real_escape_string($input->gc['aid']) ."), 2) as percentage
    FROM ip_ptc 
    WHERE ad_id=" . $db->real_escape_string($input->gc['aid']) . 
    
   " GROUP BY Country
    UNION ALL
    SELECT 'Total Clicks' ip, COUNT(ip) as sum,COUNT(ip) as sum,COUNT(ip) as sum,'100.00'
    
    FROM ip_ptc
    WHERE ad_id=" . $db->real_escape_string($input->gc['aid']);

it is showing same count results for views,interactions and clicks like below.

在此处输入图像描述

I know this is because country is not passed in count statement but getting no idea how to do this

You may use conditional aggregation here along with ROLLUP :

SELECT
    COALESCE(Country, 'Total Clicks') AS Country,
    SUM(type = 'view') AS views,
    SUM(type = 'interactions') AS interactions,
    SUM(type = 'click') AS clicks
FROM ip_ptc
WHERE
    ad_id = ?
GROUP BY
    Country WITH ROLLUP;

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