问题描述
COUNTRY LEVEL NUM_OF_DUPLICATES
US 9 6
US 8 24
US 7 12
US 6 20
US 5 39
US 4 81
US 3 80
US 2 430
US 1 178
US 0 430
COUNTRY LEVEL NUM_OF_DUPLICATES POOL
US 9 6 6
US 8 24 30
US 7 12 42
US 6 20 62
US 5 39 101
US 4 81 182
US 3 80 262
US 2 130 392
US 1 178 570
US 0 254 824
现在我想过滤数据并只在 POOL
COUNTRY LEVEL NUM_OF_DUPLICATES POOL
US 9 6 6
US 8 24 30
US 7 12 42
US 6 20 62
US 5 39 101
US 4 81 182
US 3 80 262
US 2 130 392
请告诉我您的想法。提前致谢。
解决方法
declare @t table(Country varchar(5),Level int,Num_of_Duplicates int)
insert into @t(Country,Level,Num_of_Duplicates)
values
('US',9,6),('US',8,24),7,12),6,20),5,39),4,81),3,80),2,130/*-92*/),1,178),430);
select *,sum(Num_of_Duplicates) over(partition by country order by Level desc),(sum(Num_of_Duplicates) over(partition by country order by Level desc)-Num_of_Duplicates) / 300 as flag,--any row which starts before 300 will have flag=0
--or
case when sum(Num_of_Duplicates) over(partition by country order by Level desc)-Num_of_Duplicates < 300 then 1 else 0 end as startsbefore300
from @t;
select *
from
(
select *,sum(Num_of_Duplicates) over(partition by country order by Level desc) as Pool
from @t
) as t
where Pool - Num_of_Duplicates < 300 ;
,
我使用了两个临时表来得到答案。
DECLARE @t TABLE(Country VARCHAR(5),[Level] INT,Num_of_Duplicates INT)
INSERT INTO @t(Country,Num_of_Duplicates)
VALUES ('US',130),254);
SELECT
Country,Num_of_Duplicates,SUM (Num_of_Duplicates) OVER (ORDER BY id) AS [POOL]
INTO #temp_table
FROM
(
SELECT
Country,level,ROW_NUMBER() OVER (ORDER BY country) AS id
FROM @t
) AS A
SELECT
[POOL],ROW_NUMBER() OVER (ORDER BY [POOL] ) AS [rank]
INTO #Temp_2
FROM #temp_table
WHERE [POOL] >= 300
SELECT *
FROM #temp_table WHERE
[POOL] <= (SELECT [POOL] FROM #Temp_2 WHERE [rank] = 1 )
DROP TABLE #temp_table
DROP TABLE #Temp_2