2016-06-21 89 views
2

我的問題如下,ServiceTypeWithAvgPriceBelowAvgServicePrice是一個視圖,提供服務類型的詳細信息,其平均價格低於平均服務價格。使用樣本數據,下面的查詢應該產生以下結果:sql,比較子查詢中的聚合avg函數

ServiceType    | ServiceTypeAvgPrice | ServiceAvgPrice 
3rd drafting    | 280    | 522.7083 
4th drafting    | 320    | 522.7083 
client consultation  | 172.5    | 522.7083 
design selection   | 300    | 522.7083 
initial consultation  |  0    | 522.7083 

樣本數據

Description    Actual Price 
initial consultation $0 
initial consultation $0 
design selection  $300 
drafting    $1200 
council approval  $600 
client consultation  $360 
develop design   $2070 
client consultation  $180 
client consultation  $180 
client consultation  $135 
initial consultation $0 
design selection  $300 
drafting    $1200 
council approval  $600 
client consultation  $90 
1st drafting   $1920 
2nd drafting   $920 
3rd drafting   $280 
council approval  NULL 
initial consultation $0 
initial consultation $0 
design selection  $300 
drafting    $1500 
council approval  $600 
client consultation  $90 
4th drafting   $320 
initial consultation $0 

我試圖找回預期的實際總平均低於5個平均值價格,但是我很難將每個獨特描述的平均值與總價進行比較。我試圖子查詢,如下所示,

select avg(actualPrice) as serviceytpeAvg 
from service 
having avg(actualprice) > (
        select avg(actualprice) 
        from service 
        group by descrption) 

但被拒絕,因爲它不能超過的子查詢一個返回值。解決辦法是什麼?

回答

2

您可以使用OUTER APPLY

SELECT s.[Description] as ServiceType, 
     AVG(s.[Actual Price]) as ServiceTypeAvgPrice , 
     AvgPrice as ServiceAvgPrice 
FROM [Service] s 
OUTER APPLY (
    SELECT AVG(s.[Actual Price]) as AvgPrice 
    FROM [Service] s) p 
GROUP BY s.[Description], AvgPrice 
HAVING AVG(s.[Actual Price]) < AvgPrice 

或者簡單:

SELECT s.[Description] as ServiceType, 
     AVG(s.[Actual Price]) as ServiceTypeAvgPrice , 
     (SELECT AVG([Actual Price]) FROM [Service]) as ServiceAvgPrice 
FROM [Service] s 
GROUP BY s.[Description] 
HAVING AVG(s.[Actual Price]) < (SELECT AVG([Actual Price]) FROM [Service]) 

輸出:

ServiceType    ServiceTypeAvgPrice ServiceAvgPrice 
3rd drafting   280,00    505,5769 
4th drafting   320,00    505,5769 
client consultation  172,50    505,5769 
design selection  300,00    505,5769 
initial consultation 0,00    505,5769 
+0

非常感謝你 –

+0

是我的榮幸! :)說最好的方式謝謝你是upvote /接受有用的答案:) – gofr1