Skip to content

Instantly share code, notes, and snippets.

@keithbloom
Created October 27, 2011 07:03
Show Gist options
  • Save keithbloom/1318949 to your computer and use it in GitHub Desktop.
Save keithbloom/1318949 to your computer and use it in GitHub Desktop.
TopN Stored Procedure
SELECT TOP 5 description, hit_count
CREATE PROCEDURE dbo.media_TopNCategories
(
@category varchar(300),
@TopN int
)
as
CREATE TABLE #top_results (
id [int] IDENTITY(1, 1),
description [varchar] (300),
hit_count [int]
)
INSERT #top_results (description, hit_count)
SELECT m.description, m.hit_count
FROM dbo.media m
JOIN dbo.media_categories mc
on mc.id = m.category_id
WHERE mc.description = @category
ORDER BY m.hit_count DESC
SELECT id, description, hit_count
FROM #top_results
WHERE id < = @TopN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment