如何在SQL的嵌套联接中使用GroupBy

时间:2018-10-28 10:53:18

标签: sql mariadb

以下SQL语句返回用户名,IP地址,持续时间,流量和上次访问。

            SELECT username, SUBSTRING_INDEX( callingstationid, '=', 1 ) as IP,
                   SUM(acctsessiontime) as `duration`, count(username) as Count, 
                   (SUM(`acctinputoctets`)+SUM(`acctoutputoctets`))/1000/1000/1000 as GBytes, 
                   MAX(acctstoptime) as `last visit`
            FROM radacct
            GROUP BY username

enter image description here

我想将其与“国家/地区”表一起加入,并按国家/地区分组,以便我知道每个国家/地区使用了多少流量,以及该国家/地区上次访问的时间。

我无法正确加入:

    SELECT  c.country, 
            round(GBytes, 2),  
            Count, 
            duration as `Total Time Spent`,
            `last visit`
            FROM (
                SELECT username, 
                       SUBSTRING_INDEX( callingstationid, '=', 1 ) as IP,        
                       SUM(acctsessiontime) as `duration`, count(username) as Count,                  
                       (SUM(`acctinputoctets`)+SUM(`acctoutputoctets`))/1000/1000/1000 as GBytes,
                       MAX(acctstoptime) as `last visit`
                FROM radacct
                GROUP BY username
            ) filtered_radacct
            JOIN u_cache_db.`global_ip` c ON c.ip = filtered_radacct.IP
            GROUP BY c.country
            order by GBytes DESC;

我知道这个数字不正确。

enter image description here

1 个答案:

答案 0 :(得分:0)

您还需要在顶级查询的所有字段上使用聚合函数,即

SELECT  c.country, 
        round(SUM(GBytes), 2),  
        SUM(Count), 
        SUM(duration) as `Total Time Spent`,
        MAX(`last visit`)