我正在使用sqlite3,并试图获取不同组的中位数。我目前正在使用以下查询
with data as (
select
t1.Name,
t1.Direction,
t1.Time a,
t2.Time b
from
cart t1 join cart t2 on t1.Time < t2.Time and t1.Name = t2.Name and t1.Direction = t2.Direction)
select Name, Direction, (a+b)/2.0 val from data order by Name, Direction, val
输出以下内容:
"Name" "Direction" "val"
"asdf" "w" "1.5"
"asdf" "w" "2.0"
"asdf" "w" "2.5"
"asdf" "z" "3.5"
"asdf" "z" "4.0"
"asdf" "z" "4.5"
"fdas" "w" "7.5"
"fdas" "w" "8.0"
"fdas" "w" "8.5"
"fdas" "z" "5.5"
"fdas" "z" "6.0"
"fdas" "z" "6.5"
从这一点出发,我想找到所有唯一的“名称/方向”对的中值。
预期结果:
Name Direction Val
asdf w 2.0
asdf z 4.0
fdas w 8.0
fdas z 6.0
或者如果更容易使用,还可以使用以下输出将“名称”和“方向”合并为一个唯一的ID
Name Val
asdfw 2.0
asdfz 4.0
fdasw 8.0
fdasz 6.0
原始表格数据如下:
"Name" "Direction" "Time"
"fdas" "w" "8"
"fdas" "w" "9"
"fdas" "w" "7"
"fdas" "z" "7"
"fdas" "z" "6"
"fdas" "z" "5"
"asdf" "z" "5"
"asdf" "z" "4"
"asdf" "z" "3"
"asdf" "w" "3"
"asdf" "w" "2"
"asdf" "w" "1"
通过以下查询,我已经更加接近了。剩下的唯一问题是找到所需的偏移量查询。目前,我已经使用以下offset 3
对其进行了硬编码,但是需要获取中心行。我已经尝试过(select idx from calcs where data2.Name = calcs.Name and data2.Direction = calcs.Direction)
,但是随后出现此错误no such table: calcs: with data2
。
with data2 as (
with data as (
select
t1.Name,
t1.Direction,
t1.Time a,
t2.Time b
from
cart t1 join cart t2 on t1.Time < t2.Time and t1.Name = t2.Name and t1.Direction = t2.Direction)
select Name, Direction, (a+b)/2.0 c from data order by Name, Direction, c
) select
Name,
Direction,
(select c from
(select c from data2 where data2.Name = calcs.Name and data2.Direction = calcs.Direction
order by c
limit 1
offset 2 ) subset
order by subset.c) tt
from
(select Name, Direction, round(COUNT(*)/2.0) idx from data2 group by Name, Direction) calcs
答案 0 :(得分:0)
使用另一个子查询
with data as (
select
t1.Name,
t1.Direction,
t1.Time a,
t2.Time b
from
cart t1 join cart t2
on t1.Time < t2.Time and t1.Name = t2.Name
and t1.Direction = t2.Direction
),
data2 as
(
select Name, Direction,
(a+b)/2.0 as val
from data
order by Name, Direction, val
) select Name,Direction,avg(val) as mdval from data2 group by
Name,Direction
或者仅在第二个查询中使用聚合
with data as (
select
t1.Name,
t1.Direction,
t1.Time a,
t2.Time b
from
cart t1 join cart t2 on t1.Time < t2.Time and t1.Name = t2.Name and t1.Direction = t2.Direction
)
select Name, Direction, avg((a+b)/2.0) as val
from data group by Name, Direction
order by Name, Direction, val