2012-09-19 66 views
1

我想將同一個表的不同結果合併爲一個大的結果。mysql加入同一個表的不同結果集

SELECT host_name,stats_avgcpu,stats_avgmem,stats_avgswap,stats_avgiowait 
    FROM sar_stats,sar_hosts,sar_appgroups,sar_environments 
    WHERE stats_host = host_id 
    AND host_environment = env_id 
    AND env_name = 'Staging 2' 
    AND host_appgroup = group_id 
    AND group_name = 'Pervasive' 
    AND DATE(stats_report_time) = DATE_SUB(curdate(), INTERVAL 1 DAY) 

SELECT AVG(stats_avgcpu),AVG(stats_avgmem),AVG(stats_avgswap),AVG(stats_avgiowait) 
FROM sar_stats 
WHERE stats_id = "stat_id of the first query" and DATE(stats_report_time) 
    BETWEEN DATE_SUB(curdate(), INTERVAL 8 DAY) and DATE_SUB(curdate(), INTERVAL 1 DAY) 

SELECT AVG(stats_avgcpu),AVG(stats_avgmem),AVG(stats_avgswap),AVG(stats_avgiowait) 
FROM sar_stats 
WHERE stats_id = "stat_id of the first query" and DATE(stats_report_time) 
    BETWEEN DATE_SUB(curdate(), INTERVAL 31 DAY) and DATE_SUB(curdate(), INTERVAL 1 DAY) 

所需的輸出會是這樣的......

host_name|stats_avgcpu|stats_avgmem|stats_avgswap|stats_avgiowait|7daycpuavg|7daymemavg|7dayswapavg|7dayiowaitavg|30daycpuavg|30daymemavg|....etc 

SQL小提琴 http://sqlfiddle.com/#!8/4930b/3

+2

如果你創建了一個工作會更容易使用[SQL Fiddle](http://sqlfiddle.com/)中的DDL和DML模型。在這一點上,我們無法知道每個表格會發送什麼數據。如果你不創建一個sql小提琴,那麼至少要提供表結構和示例數據。 – Taryn

回答

2

好像這是你想要的。我更新了第一次查詢中使用適當的ANSI JOIN語法,然後爲他們的stats_host場通過LEFT JOIN加入了額外的兩個查詢:

SELECT s.stats_host, 
    h.host_name, 
    s.stats_avgcpu, 
    s.stats_avgmem, 
    s.stats_avgswap, 
    s.stats_avgiowait, 
    s7.7dayavgcpu, 
    s7.7dayavgmem, 
    s7.7dayavgswap, 
    s7.7dayavgiowait, 
    s30.30dayavgcpu, 
    s30.30dayavgmem, 
    s30.30dayavgswap, 
    s30.30dayavgiowait 
FROM sar_stats s 
INNER JOIN sar_hosts h 
    on s.stats_host = h.host_id 
INNER JOIN sar_appgroups a 
    on h.host_appgroup = a.group_id 
    and a.group_name = 'Pervasive' 
INNER JOIN sar_environments e 
    on h.host_environment = e.env_id 
    and e.env_name = 'Staging 2' 
LEFT JOIN 
(
    SELECT s.stats_host, 
    AVG(s.stats_avgcpu) AS '7dayavgcpu', 
    AVG(s.stats_avgmem) AS '7dayavgmem', 
    AVG(s.stats_avgswap) AS '7dayavgswap', 
    AVG(s.stats_avgiowait) AS '7dayavgiowait' 
    FROM sar_stats s 
    WHERE DATE(stats_report_time) BETWEEN DATE_SUB(curdate(), INTERVAL 8 DAY) AND DATE_SUB(curdate(), INTERVAL 1 DAY) 
    GROUP BY s.stats_host 
) s7 
    on s.stats_host = s7.stats_host 
LEFT JOIN 
(
    SELECT s.stats_host, 
    AVG(s.stats_avgcpu) AS '30dayavgcpu', 
    AVG(s.stats_avgmem) AS '30dayavgmem', 
    AVG(s.stats_avgswap) AS '30dayavgswap', 
    AVG(s.stats_avgiowait) AS '30dayavgiowait' 
    FROM sar_stats s 
    WHERE DATE(s.stats_report_time) BETWEEN DATE_SUB(curdate(), INTERVAL 31 DAY) AND DATE_SUB(curdate(), INTERVAL 1 DAY) 
    GROUP BY s.stats_host 
) s30 
    on s.stats_host = s30.stats_host 
WHERE DATE(s.stats_report_time) = DATE_SUB(curdate(), INTERVAL 1 DAY); 

看到SQL Fiddle with Demo