如何在sql中找到中位数。我正在尝试
select
date,
sum(amount),
median(amount),
count(user)
from table
group by 1
它显示一个错误
函数中位数(双精度)不存在
答案 0 :(得分:0)
尝试此标准sql是否有效。
select
t.[date]
,sum(amount) ttl_amount
,(select sum(s.amount) / (select ((count(*) + 1) % 2) + 1 from @table s where s.[date] = t.[date])
from (select s.amount
from @table s
where t.date = s.date
order by s.amount asc
offset (select ((count(*) - (count(*) + 1) % 2) / 2) from @table s where s.[date] = t.[date]) rows fetch next
(select ((count(*) + 1) % 2) + 1 from @table s where s.[date] = t.[date]) rows only ) s ) median
,count(distinct [user]) dst_user
from @table t
group by [date]