返回符合特定条件的每组的10%记录

时间:2017-08-14 21:54:14

标签: sql

我正在尝试查询具有多个组的表,以获得满足特定条件的每个组中10%的系统。

这是数据:

30

表中有更多这样的记录。例如,我需要在每个位置找到10%的计算机名称,其评级为3093.

3 个答案:

答案 0 :(得分:2)

如果您使用的是SQL Server,可以在PERCENT声明中使用select

SELECT TOP 10 PERCENT * FROM tablename WHERE RATING=3093;

答案 1 :(得分:2)

这应该适用于Oracle,尽管样本数据不足以获得10%的样本......

create table tablename as
select '4FH6V1' as ComputerName, 'AZ1' as Location, '3093' as Rating from dual union all
select '0GLYQ1' as ComputerName, 'AZ1' as Location, '3093' as Rating from dual union all
select 'P191R1' as ComputerName, 'AZ1' as Location, '3093' as Rating from dual union all
select '7CMJ02' as ComputerName, 'AZ3' as Location, '3392' as Rating from dual union all
select '8W2QS1' as ComputerName, 'AZ4' as Location, '3093' as Rating from dual union all
select 'K9CHX1' as ComputerName, 'AZ7' as Location, '3192' as Rating from dual union all
select '3XZNS1' as ComputerName, 'AZ7' as Location, '3093' as Rating from dual union all
select '79RGX1' as ComputerName, 'AZ9' as Location, '3192' as Rating from dual union all
select '02BR22' as ComputerName, 'AZ3' as Location, '2593' as Rating from dual
;

with cte1 as (
select
   x.ComputerName
  ,x.Location
  ,x.Rating
  ,count(1) over (partition by Location) as location_total
  ,row_number() over (partition by Location order by ComputerName) as location_position
  ,row_number() over (partition by Location order by ComputerName) / count(1) over (partition by Location) as location_pct
from tablename x
where x.Rating = 3093
)
select *
from cte1
where location_pct <= 0.1

答案 2 :(得分:0)

您使用的是SQL Server,可以使用apply

select tt.*
from (select distinct location from t where t.rating = 3093) l apply
     (select top (10) PERCENT t.*
      from t
      where t.location = l.location and t.rating = 3093
     ) tt