Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 TOP 5 Per Group

Author  Topic 

snipered
Starting Member

9 Posts

Posted - 2012-03-12 : 12:32:40
Hi, i am trying to get the TOP 5 for every group but it never works. I have tried row_number with little success. Anybody have any ideas?

Thanks in advance

DECLARE @Year int
SET @Year = (Select datepart(year,getdate()))

SELECT dt.IDCode, intWeek, intYear, dt.KeyFigure
FROM
(
SELECT Y.IDCode ,
intWeek, intYear,
KeyFigure = (SELECT count(coID) FROM TableB B
INNER JOIN TableC C ON C.Date = DATEADD(dd, 0, DATEDIFF(dd, 0, B.inputDate))
INNER JOIN TableR R ON R.IDCode = B.IDCode
WHERE C.intYear = H.intYear
AND C.intWeek = H.intWeek
AND C.Calender = 'FirstCalender'
AND (typ = 'pppp' OR typ = 'llll')
AND R.Des = 'SomeStuff'
AND ((@Site IS NULL) OR (B.Site = @Site))
AND Cat = 'SomeCategory'
and El = 'sdhsjhjh'
and Sub IN ('2', '4', '43', '1', '99', '123'))
FROM TableY Y
INNER JOIN TableG G On G.gID = Y.IDCode
INNER JOIN TableH H ON H.Dates = DATEADD(dd, 0, DATEDIFF(dd, 0, Y.inputDate)
WHERE G.gMat = 'xxx'
AND H.Calender = 'FirstCalender'
AND (typ = 'pppp' OR typ = 'llll')
AND (H.intYear = @Year or H.intYear = (@Year -1 ))
)dt
GROUP BY dt.intYear,dt.intWeek, dt.IDCode, dt.KeyFigure

GilaMonster
Master Smack Fu Yak Hacker

4507 Posts

Posted - 2012-03-12 : 12:34:39
Top 5 by what? What column or set of columns says whether a row is number 2 or number 122?
Is a group defined by dt.intYear,dt.intWeek, dt.IDCode, dt.KeyFigure?

--
Gail Shaw
SQL Server MVP
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-03-12 : 12:36:34
show some sample data and show how you want TOP 5 to appear

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

snipered
Starting Member

9 Posts

Posted - 2012-03-18 : 20:30:20
Hi sorry for late reply, just been very sick.

I have a stacked bar graph. So for every Period within that year, i want to show the top 5 keyfigures. So the stacked bar will only have 5 items instead of the 60 odd it has now.

Any ideas?
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-03-19 : 00:21:18
just use inside your query

SELECT columns...
FROM
(
--The below is your current query
SELECT ROW_NUMBER() OVER (PARTITION BY YourPeriodColumn ORDER BY KeyValue DESC) AS Rn,your other columns...
FROM...
)t
WHERE Rn<=5


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -