2个不同的AVG列在1表中选择

时间:2017-04-20 12:31:07

标签: mysql sql

我正在尝试制作一张桌子,在没有市场的地区展示市场区域的扒手AVG和扒手的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

4 个答案:

答案 0 :(得分:1)

假设distict中的market是唯一的,那么您可以使用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 :(得分: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;

希望这会有所帮助: - )

答案 2 :(得分:1)

请尝试以下方法......

average

首先,列出zakkenrollerij within中符合without条件的所有值的列表。在此阶段不会尝试执行计算。第二列适用于符合NULL条件的值 - 在此阶段,其所有值都将设置为without

然后使用UNION运算符将此列表与ROUND( AVG() )对应列表垂直连接。

然后,加入列表会对其列执行{{1}}个操作。

如果您有任何问题或意见,请随时发表评论。

答案 3 :(得分:0)

您现在要经过两次表,在不同的名称下选择两次相同的变量:

round(平均值),0) as districts_with_markets, round(avg(average),0) as 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