27,579
社区成员
发帖
与我相关
我的任务
分享
create table tb(a1 varchar(10),a2 int,a3 int)
insert into tb values('a', 3 ,5)
insert into tb values('a', 7 ,6)
insert into tb values('a', 4 ,3)
insert into tb values('a', 9 ,4)
insert into tb values('b', 9 ,3)
insert into tb values('b', 7 ,6)
insert into tb values('b', 8 ,9)
insert into tb values('b', 6 ,12)
insert into tb values('b', 5 ,15)
go
select m.a1 , a2 =
cast(avg(n.a2*1.0) as decimal(18,1)),
m.a3 from
(select a1 , count(1) a2 , cast(avg(a3*1.0) as decimal(18,1)) a3 from tb group by a1 ) m,
(select t.* , px = (select count(1) from tb where a1 = t.a1 and (a2 < t.a2 or (a2 = t.a2 and a3 < t.a3))) + 1 from tb t) n
where m.a1 = n.a1 and ((m.a2 % 2 = 1 and n.px = m.a2 / 2 + 1) or (m.a2 % 2 = 0 and (n.px = m.a2 / 2 + 1 or n.px = m.a2 / 2)))
group by m.a1 , m.a3
drop table tb
/*
a1 a2 a3
---------- -------------------- --------------------
a 5.5 4.5
b 7.0 9.0
(所影响的行数为 2 行)
*/
SELECT a1,
a2=CAST(((SELECT MAX(a2) FROM (SELECT TOP 50 PERCENT a2 FROM #tp p WHERE t.a1=p.a1 ORDER BY a2)M)
+
(SELECT MIN(A2) FROM (SELECT TOP 50 PERCENT A2 FROM #TP P WHERE P.A1=T.A1 ORDER BY a2 DESC)N))/2.0 AS DECIMAL(5,2))
,cast(AVG(a3*1.0) AS DECIMAL(5,2))AS a3
FROM #tp t
GROUP BY a1
a1 a2 a3
---- --------------------------------------- ---------------------------------------
a 5.50 4.50
b 7.00 9.00
(2 row(s) affected)
--> 测试数据:#
if object_id('tempdb.dbo.#') is not null drop table #
create table #(a1 varchar(8), a2 float, a3 float)
insert into #
select 'a', 3, 5 union all
select 'a', 7, 6 union all
select 'a', 4, 3 union all
select 'a', 9, 4 union all
select 'b', 9, 3 union all
select 'b', 7, 6 union all
select 'b', 8, 9 union all
select 'b', 6, 12 union all
select 'b', 5, 15
-- 临时表
select id = identity(int,1,1), * into #temp from # order by a1, a2
select a1,
a2 = avg(case when n between nx/2 and nx/2+nx%2 then a2 end),
a3 = avg(a3)
from
(
select *,
n = id - (select isnull(max(id),0)+1 from #temp where a1<t.a1),
nx = (select count(1) from #temp where a1=t.a1) - 1
from #temp t
) a
group by a1
/*
a1 a2 a3
-------- ---------------------- ----------------------
a 5.5 4.5
b 7 9
*/
SELECT a1,cast(SUM(a2)*1.0/COUNT(a2) AS DECIMAL(6,1))[a2]
,cast(SUM(a3)*1.0/COUNT(a3) AS DECIMAL(6,1))[a3]
FROM #tb t
GROUP BY t.a1
a1 a2 a3
---------- --------------------------------------- ---------------------------------------
a 3.5 5.5
b 8.0 6.0
(2 row(s) affected)
--> 测试数据:#1
if object_id('tempdb.dbo.#1') is not null drop table #1
create table #1([a1] varchar(1),[a2] int,[a3] int)
insert #1
select 'a',3,5 union all
select 'a',4,6 union all
select 'b',9,3 union all
select 'b',8,6 union all
select 'b',7,9
select a1,cast(AVG(a2*1.0) as numeric(12,1)),cast(AVG(a3*1.0) as numeric(12,1))
from #1
group by a1