Sql示例说明如何分组后求中间值--【叶子】

本文介绍了一种使用SQL查询分组后中间值的方法,并通过具体示例展示了如何实现这一功能。不同于平均值,中间值需要根据分组内的元素数量确定。

这里所谓的分组后求中间值是个什么概念呢?

我举个例子来说明一下:

假设我们现在有下面这样一个表:

 

type        name price

----------- ---- ------------

2           A    5.4

2           A    3.7

2           B    4.3

1           B    4.7

2           B    6.7

2           B    9.8

3           a    3.0

3           a    4.0

3           a    10.0

3           a    20.0

 

我们要得到什么样的效果呢?

typename进行分组后求中间值:

 

是不是就是这样呢:

 

select [type],name,AVG(price) from @table

group by type,name

 

/*

type        name

----------- ---- ---------------------------------------

2           A    4.550000

3           a    9.250000

1           B    4.700000

2           B    6.933333

 

*/

不是的,我所说的中间值和平均数还不太一样,平均数就是均值,但是中间值是说分组如果有奇数个就是中间那个,如果有偶数个就是中间两个值的均值。

例如上面数据中3a分组后有341020四个数,那中间值就是410个均值。

例如上面按2B分组后有4.3 和6.7 及9.8三个值,那中间值就是6.7

 

我们如何能达到这样效果呢,写个简单的例子:

 

declare @table table ([type] int,name varchar(1),price numeric(3,1))

insert into @table

select 2,'A',5.4 union all

select 2,'A',3.7 union all

select 2,'B',4.3 union all

select 1,'B',4.7 union all

select 2,'B',6.7 union all

select 2,'B',9.8 union all

select 3,'a',3 union all

select 3,'a',4 union all

select 3,'a',10 union all

select 3,'a',20

 

--sql查询如下:

 

;with maco as

(

    select

        [type],name,price,

        m_asc=row_number() over(partition by type,name order by price),

        m_desc=row_number() over(partition by type,name order by price desc)

    from @table

)

--select * from liang

select [type],name,avg(price) as price

from maco

where m_asc in(m_desc,m_desc+1,m_desc-1)

group by type,name

order by type,name

 

/*

type        name price

----------- ---- -----------

1           B    4.700000

2           A    4.550000

2           B    6.700000

3           a    7.000000

*/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值