July 20, 2010 at 6:15 pm
Picture this:
DECLARE @test-2 TABLE(Item int, val int)
INSERT @test-2 SELECT 1, 90
INSERT @test-2 SELECT 2, 80
INSERT @test-2 SELECT 3, 70
INSERT @test-2 SELECT 4, 60
INSERT @test-2 SELECT 5, 50
INSERT @test-2 SELECT 6, 40
INSERT @test-2 SELECT 7, 30
INSERT @test-2 SELECT 8, 20
INSERT @test-2 SELECT 9, 10
SELECT TOP 5 Item, val FROM @test-2 ORDER BY VAL DESC
gives me the top 5 items by value (1,2,3,4,5)
1 90
2 80
3 70
4 60
5 50
but if the 6th, or 7th, or 8th (etc.) item, macthes the last one, I need to include it.
FOR example:
DECLARE @test-2 TABLE(Item int, val int)
INSERT @test-2 SELECT 1, 90
INSERT @test-2 SELECT 2, 80
INSERT @test-2 SELECT 3, 70
INSERT @test-2 SELECT 4, 60
INSERT @test-2 SELECT 5, 50
INSERT @test-2 SELECT 6, 50
INSERT @test-2 SELECT 7, 50
INSERT @test-2 SELECT 8, 20
INSERT @test-2 SELECT 9, 10
What I want is
1 90
2 80
3 70
4 60
5 50
6 50
7 50
Must be a simple way with going RBAR
Thanks Phil
July 20, 2010 at 6:48 pm
This should do it
SELECT TOP (5) WITH TIES Item, val FROM @test-2 ORDER BY VAL DESC
July 20, 2010 at 9:05 pm
Thanks, that's it. Simple, I just didn't know about it... Phil
July 20, 2010 at 9:11 pm
@Ron,
Excellent! I see I need to look into WITH TIES a bit now.
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
July 21, 2010 at 11:14 am
Joe Celko (7/21/2010)
A more portable, ANSI/ISO Standard version, with ordinal functions:CREATE TABLE Tests
(Item_nbr INTEGER NOT NULL PRIMARY KEY,
something_val INTEGER NOT NULL);
INSERT INTO Tests VALUES
(1, 90), (2, 80), (3, 70), (4, 60), (5, 50), (6, 40), (7, 30), (8, 20), (9, 10);
SELECT *
FROM (SELECT Item_nbr, something_val,
ROW NUMBER() OVER (ORDER BY something_val DESC) AS score
FROM Tests)
WHERE score <= @my_top_limit;
Aside from the syntax errors this won't work because he wants to return ties, which ROW_NUMBER will not do. This will work ...
SELECT *
FROM
(SELECT Item_nbr,
something_val,
DENSE_RANK() OVER (ORDER BY something_val DESC) AS score
FROM #Tests) sq
WHERE score <= 5;
I like the WITH TIES though ... I didn't know that existed.
July 21, 2010 at 12:43 pm
bitbucket-25253 (7/20/2010)
This should do it
SELECT TOP (5) WITH TIES Item, val FROM @test-2 ORDER BY VAL DESC
Very cool! Didn't know about WITH TIES.
Thanks Mr. Bucket
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply