我正在使用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
使用另一个子查询
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