2017-04-20 91 views
1

我試圖製作一張表,顯示扒手的AVG在市場區和AVG的扒手在沒有市場的地區。1個表中的2個不同的AVG列與選擇

我想有這樣的輸出:

district with market | district without market 
---------------------------------------------- 
269     | 34 

而是我得到這個:

district with market | district without market 
---------------------------------------------- 
269     | 269 
34     | 34 

這是我使用的查詢:

select round(avg(average),0) as districts_with_markets, round(avg(average),0) as districts_without_markets 
from zakkenrollerij 
where wijk in (select district 
       from market) 
union 
select round(avg(average),0) as districts_with_markets, round(avg(average),0) as districts_without_markets 
from zakkenrollerij 
where wijk not in (select district 
       from market) 

希望有人可以幫助我:D

回答

1

假設distictmarket唯一的,那麼你可以用一個left join和有條件聚集做到這一點:

select round(avg(case when m.district is not null then average end), 0) as districts_with_markets, 
     round(avg(case when m.district is null then average end), 0) as districts_without_markets 
from zakkenrollerij z left join 
    market m 
    on m.district = z.wijk; 

如果不是這種情況,那麼使用子查詢和標誌:

select round(avg(case when hasMarketFlag then average end), 0) as districts_with_markets, 
     round(avg(case when not hasMarketFlag then average end), 0) as districts_without_markets 
from (select z.*, 
      (exists (select 1 
         from market m 
         where m.district = z.wijk 
        ) 
      ) as hasMarketFlag 
     from zakkenrollerij z; 
1

試試這個: -

Select sum(dist_with_markets) as district_with_markets, 
     sum(dist_without_markets) as district_without_markets 
from 
(
select round(avg(average),0) as dist_with_markets, 0 as dist_without_markets 
from zakkenrollerij 
where wijk in (select district 
       from market) 
union 
select 0 as dist_with_markets, round(avg(average),0) as dist_without_markets 
from zakkenrollerij 
where wijk not in (select district 
       from market)               ) a; 

希望這有助於:-)

0

你現在要低谷表兩次,選擇同一個變量兩次以不同的名字:

輪(AVG(平均值),0)作爲districts_with_markets,輪(AVG(平均值),0)作爲districts_without_market

之後您可以使用CASE來選擇具有特定條件的變量,而不是聯合表格。這應該給想要的結果:

select round(avg(case when wijk in (select district from market) then average else null end),0) as districts_with_markets, 
    round(avg(case when wijk not in (select district from market) then average else null end),0) as districts_without_markets 
from zakkenrollerij 
1

請嘗試以下...

SELECT ROUND(AVG(with_markets)) AS districts_with_markets, 
     ROUND(AVG(without_markets)) AS without_markets 
FROM (SELECT average AS with_markets 
       NULL AS without_markets 
     FROM zakkenrollerij 
     WHERE wijk IN (SELECT district 
         FROM market) 
     UNION 
     SELECT NULL, 
       average 
     FROM zakkenrollerij 
     WHERE wijk NOT IN (SELECT district 
          FROM market) 
    ) AS tempTable; 

這將啓動通過形成內zakkenrollerij有資格作爲withinaverage所有值的列表。在這個階段沒有嘗試執行計算。第二列用於符合without的值 - 在此階段所有值都將設置爲NULL

然後使用UNION運算符將此列表與其對應的without垂直連接。

加入列表然後在其列上執行ROUND(AVG())操作。

如果您有任何問題或意見,請隨時發佈相應評論。

相關問題