Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
Hi,I am having problems writing an SQL query in SQL Server 2005, i have written the following querySelect comp.Name as 'Competition', c.Name, Count(c.ID) as 'Count'From ScoutingLeagues slJoin Competition comp on comp.ID = sl.CompetitionIDJoin Seasons sea on sea.ID = 148Join ClubLeagueMapping clm on clm.CompetitionID = comp.IDJoin Club c on c.ID = clm.ClubIDJoin Squad s on s.ClubID = c.IDJoin ScoutingTeam st on st.SquadID = s.IDJoin ScoutingReport sr on sr.ID Between st.MinScoutReportID And MaxScoutReportID And sr.ReportDate Between sea.StartDate And sea.EndDateWhere sl.ScoutingLeagueType = 0And clm.DateEntered <= sea.StartDate -- entered league before season startAnd (clm.DateLeft is null or clm.DateLeft >= sea.EndDate) -- still in league or left before season endAnd comp.ID = 0Group By comp.Name, c.Name, c.IDwhich returns the following results
Competition Club CountPremier a 8 Premier b 7 Premier c 6Premier d 5La Liga z 4
but i need the query to produce the following results
the count(4) represents clubs with a count of 4 etcso im just wondering if anyone has any idea how to count the number of clubs that have a specified count, i have tried a derived table but cant figure it out,thanks in advanceTim
SwePeso
Patron Saint of Lost Yaks
30421 Posts
Posted - 2008-07-16 : 07:21:06
Insert into a temporary table.From that table you do a normal PIVOT query.E 12°55'05.25"N 56°04'39.16"
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2008-07-16 : 07:21:37
May be this:-
SELECT t.Competition,SUM(CASE WHEN Count>5 THEN 1 ELSE 0 END) AS [Count>5],SUM(CASE WHEN Count=4 THEN 1 ELSE 0 END) AS [Count(4)],SUM(CASE WHEN Count=3 THEN 1 ELSE 0 END) AS [Count(3)],SUM(CASE WHEN Count=2 THEN 1 ELSE 0 END) AS [Count(2)],SUM(CASE WHEN Count=2 THEN 1 ELSE 0 END) AS [Count(1)]FROM (YourCurrentQuery)tGROUP BY t.Competition
tadhg88
Yak Posting Veteran
62 Posts
Posted - 2008-07-16 : 07:33:30
just out of interest Peso do you know if you can do a pivot on a derived tablethanks for your reply
tadhg88
Yak Posting Veteran
62 Posts
Posted - 2008-07-16 : 07:36:14
thanks for your replay visakh that was exactly what i neededthanks again Tim
SwePeso
Patron Saint of Lost Yaks
30421 Posts
Posted - 2008-07-16 : 07:36:58
Visakh showed you how.By the way, were are all Club with count of 5?E 12°55'05.25"N 56°04'39.16"
tadhg88
Yak Posting Veteran
62 Posts
Posted - 2008-07-16 : 08:13:55
oh ok i understand now, i thought you were talking about the new Pivot command introduced in SQL Server 2005...cheers for your help guys its very much appreciatedTim