2017-04-23 29 views
0

我有这个疯狂的嵌套的SQL语句,并返回是这样的:我怎么能计算出一个嵌套的SQL语句的平均?

Results

不过,我要的是使用该数据的图像在返回2列。 COL_1SUM(avgWithCriteria)/43COL_2SUM(avgWithoutCriteria)/43。我如何通过添加到我的查询下面?

SELECT 
    ((avgWithCriteria - totalAverage)/((avgWithCriteria + totalAverage)/2)) * 100 as percentDifference, 
    a.* 
FROM 
    (SELECT 
     AVG(CASE WHEN 'f' not in (has_free_parking) THEN price ELSE null END) as avgWithCriteria, 
     AVG(CASE WHEN 'f'  in (has_free_parking) THEN price ELSE null END) as avgWithoutCriteria, 
     AVG(price) as totalAverage, 
     neighbourhood_cleansed 
    FROM listings 
    WHERE city_name="berlin" 
    AND price <= 1000000 
    AND price >= -1 
    AND reviews_per_month <= 1000000 
    AND reviews_per_month >= -1 
    AND est_monthly_income <= 1000000 
    AND est_monthly_income >= -1 
    GROUP BY neighbourhood_cleansed) a; 
+0

..., SUM(avgWithCriteria)/ 43 COL_1, SUM(avgWithoutCriteria)/ 43 COL_2, 一个* .. ..... –

+0

@VanyaAvchyan可以追加到它原来的查询,请作为一个答案? –

回答

1

试试这个: - 。

SELECT percentDifference,avgWithCriteria,avgWithoutCriteria,totalAverage,neighbourhood_cleansed, 
(col1_1/43) as col1,(col2_2/43) as col2 
from 
(
SELECT a.*,SUM(avgWithCriteria) as col1_1,SUM(avgWithoutCriteria) as col2_2 
FROM 
    (
SELECT 
    ((avgWithCriteria - totalAverage)/((avgWithCriteria + totalAverage)/2)) * 100 as percentDifference, 
    a.* 
FROM 
    (SELECT 
     AVG(CASE WHEN 'f' not in (has_free_parking) THEN price ELSE null END) as avgWithCriteria, 
     AVG(CASE WHEN 'f'  in (has_free_parking) THEN price ELSE null END) as avgWithoutCriteria, 
     AVG(price) as totalAverage, 
     neighbourhood_cleansed 
    FROM listings 
    WHERE city_name="berlin" 
    AND price <= 1000000 
    AND price >= -1 
    AND reviews_per_month <= 1000000 
    AND reviews_per_month >= -1 
    AND est_monthly_income <= 1000000 
    AND est_monthly_income >= -1 
    GROUP BY neighbourhood_cleansed) a 
) a 
GROUP BY percentDifference,avgWithCriteria,avgWithoutCriteria,totalAverage,neighbourhood_cleansed 
) a; 
+0

非常感谢!这是我需要的 –

0
SELECT 
    ((avgWithCriteria - totalAverage)/((avgWithCriteria + totalAverage)/2)) * 100 as percentDifference, 
    SUM(avgWithCriteria)/43 AS col_1, 
    SUM(avgWithoutCriteria)/43 AS col_2, 
    a.* 
FROM 
    (SELECT 
     AVG(CASE WHEN 'f' not in (has_free_parking) THEN price ELSE null END) as avgWithCriteria, 
     AVG(CASE WHEN 'f'  in (has_free_parking) THEN price ELSE null END) as avgWithoutCriteria, 
     AVG(price) as totalAverage, 
     neighbourhood_cleansed 
    FROM listings 
WHERE city_name="berlin" 
AND price <= 1000000 
AND price >= -1 
AND reviews_per_month <= 1000000 
AND reviews_per_month >= -1 
AND est_monthly_income <= 1000000 
AND est_monthly_income >= -1 
GROUP BY neighbourhood_cleansed) a;