连接表获取列名和总和问题

时间:2018-02-14 11:01:06

标签: sql join

我遇到了一个问题,我在表A中存储了表B的列名,并尝试从表A和B中获取column_name和sum(column_name)

SELECT 
metric AS attribute,
SUM(metric) AS total
FROM x_instr ase
JOIN
(SELECT sites.id AS site_id, sites.name AS sitename,
    a.metric_name AS metric
FROM
    sites, servers, x_y_aiminstr_attrnames a, x_instr b
WHERE
    a.mbeanid = b.mbeanid  
    AND sites.id = b.siteid
    AND b.time BETWEEN '2018-02-09 00:00:00' AND '2018-02-09 23:59:59'
    AND b.serverid = servers.id
    AND sites.name = 'x_y_z_1'
GROUP BY metric) subquery 
ON ase.siteid = subquery.site_id
GROUP BY attribute

即使存在值,结果集也会返回零。简而言之,我的意思是我试图从2个表中提取列名和总和

1 个答案:

答案 0 :(得分:0)

尝试此操作如果内部查询为您提供结果

SELECT 
metric AS attribute,
SUM(metric) AS total
FROM x_instr ase
JOIN
(SELECT sites.id AS site_id, sites.name AS sitename,
    a.metric_name AS metric
FROM
    sites, servers, x_y_aiminstr_attrnames a, x_instr b
WHERE
    a.mbeanid = b.mbeanid  
    AND sites.id = b.siteid
    AND b.time BETWEEN '2018-02-09 00:00:00' AND '2018-02-09 23:59:59'
    AND b.serverid = servers.id
    AND sites.name = 'x_y_z_1') subquery 
ON ase.siteid = subquery.site_id
GROUP BY attribute