我知道如何计算1张桌子的中位数,但我试图在6张桌子上比较价格。到目前为止我的代码,你能帮忙吗?
select avg(price) as median from
(select row_id, price from (
(select @counter:=@counter+1 as row_id, t1.priceInt as price
from Table1 t1, (select @counter:=0) tx1
)
union all (select @counter:=@counter+1 as row_id, t2.priceInt as price
from Table2 t2, (select @counter:=0) tx2
)
union all (select @counter:=@counter+1 as row_id, t3.priceInt as price
from Table3 t3, (select @counter:=0) tx3
)
union all (select @counter:=@counter+1 as row_id, t4.priceInt as price
from Table4 t4, (select @counter:=0) tx4
)
union all (select @counter:=@counter+1 as row_id, t5.priceInt as price
from Table5 t5, (select @counter:=0) tx5
)
union all (select @counter:=@counter+1 as row_id, t6.priceInt as price
from Table6 t6, (select @counter:=0) tx6
)
) xx order by price) o1 join
(
select sum(x) AS total_rows from
(
select count(*) x from Table1 union all select count(*) x from
Table2
union all select count(*) x from Table3 union all select count(*) x
from Table4
union all select count(*) x from Table5 union all (select count(*) x
from Table6
)
) o2 where o1.row_id in (floor((o2.total_rows + 1)/2),
floor((o2.total_rows + 2)/2)))
我的错误是o1.row_id无法识别!
以下是表1的示例,每个表都有相同的列!
*** EDIT
期望的结果:250,275,300,400,500我想要300k (注意必须订购数字,如果有2个中间数字,则必须找到2个数字的平均值)
答案 0 :(得分:1)
Just" stack"将每个表中的数据放在一起,并将其作为一个列表从那时开始,将计数器放在一个级别"。对查询进行布局,以便于阅读,以便于查找别名。
select
avg(price) as median
from (
select
row_id
, price
from (
select
@counter:=@counter+1 as row_id
, price
from (
select t1.priceInt as price from Table1 t1 union all
select t2.priceInt as price from Table2 t2 union all
select t3.priceInt as price from Table3 t3 union all
select t4.priceInt as price from Table4 t4 union all
select t5.priceInt as price from Table5 t5 union all
select t6.priceInt as price from Table6 t6
) u
cross join (select @counter:=0) vars
ORDER BY u.price
) o1
cross join (
select sum(x) AS total_rows
from (
select count(*) x from Table1 union all
select count(*) x from Table2 union all
select count(*) x from Table3 union all
select count(*) x from Table4 union all
select count(*) x from Table5 union all
select count(*) x from Table6
) c
) o2
where o1.row_id in (floor((o2.total_rows + 1)/2),floor((o2.total_rows + 2)/2)))
) d
将重复的sql放置为" list"对我的经历非常有帮助。我刚才意识到在保存之前我的表名错了。它当然未经测试,但它应该可以帮助你开始。
哦,请避免在from子句中使用表或子查询之间的逗号。你会看到很多像这样的样本:
from table_x, (select @counter:=0) vars
唐'吨!它不是显式连接(它是隐含的交叉连接),使其显式:
from table_x
cross join (select @counter:=0) vars
现在每个人都知道交叉加入是非常有意义的。