all groups > sql server programming > november 2006 >
You're in the

sql server programming

group:

query to return the highest of a group of calculated totals


query to return the highest of a group of calculated totals rob.fulwell NO[at]SPAM gmail.com
11/1/2006 9:28:00 PM
sql server programming:
I have a query that calculates the number of times a given bug has been
hit:
SELECT Count(*) As CrashCount
FROM Crashes
WHERE (BugNumber = @UserBugNumber);

Now I want to know which BugNumber would return the highest number for
that query if that query iterated across all BugNumbers and what that
BugNumber is.

Thanks!

Rob.
RE: query to return the highest of a group of calculated totals Omnibuzz
11/1/2006 10:04:03 PM
untested.. but this should work..

SELECT top 1 BugNumber,Count(*) As CrashCount
FROM Crashes
group by BugNumber
order by
CrashCount desc

--
-Omnibuzz

http://omnibuzz-sql.blogspot.com/

Re: query to return the highest of a group of calculated totals Chris Lim
11/1/2006 11:17:15 PM
I'm sure someone will come up with a better solution, but this should
work:

SELECT BugNumber, COUNT(*) AS CrashCount
FROM Crashes
GROUP BY BugNumber
HAVING COUNT(*) = ( SELECT MAX(C.CrashCount)
FROM ( SELECT BugNumber, COUNT(*) AS
CrashCount
FROM Crashes
GROUP BY BugNumber
) C
)

Chris

[quoted text, click to view]
Re: query to return the highest of a group of calculated totals thomasroji NO[at]SPAM gmail.com
11/1/2006 11:34:25 PM
SELECT TOP 1 BugNumber, CrashCount
FROM (SELECT BugNumber, COUNT(*) AS CrashCount
FROM Crashes
GROUP BY BugNumber)
ORDER BY CrashCount DESC

[quoted text, click to view]
Re: query to return the highest of a group of calculated totals Chris Lim
11/2/2006 12:07:58 AM
[quoted text, click to view]

Or simply:

SELECT TOP 1 BugNumber, COUNT(*) AS CrashCount
FROM Crashes
GROUP BY BugNumber
ORDER BY COUNT(*) DESC

However this does not cater for the case where there are multiple
BugNumbers with the same maximum (not sure if that matters to the OP
though as it wasn't stated).
Re: query to return the highest of a group of calculated totals Omnibuzz
11/2/2006 1:51:02 AM
[quoted text, click to view]

In that case you can use..
SELECT TOP 1 WITH TIES ...

--
-Omnibuzz

http://omnibuzz-sql.blogspot.com/

Re: query to return the highest of a group of calculated totals Chris Lim
11/2/2006 2:09:18 AM
[quoted text, click to view]

Cool... never seen that before!
Re: query to return the highest of a group of calculated totals rob.fulwell NO[at]SPAM gmail.com
11/2/2006 10:43:19 AM
Thanks to all for the timely replies. You saved my bacon!

Cheers,

Rob.
Re: query to return the highest of a group of calculated totals Augustin Prasanna
12/4/2006 12:00:00 AM
select top 1 BugNumber from
(select count(1) as crashcount, BugNumber from @Crashes group by id ) tmp
order by crashcount desc

Regards,
Augustin
http://augustinprasanna.blogspot.com

[quoted text, click to view]

AddThis Social Bookmark Button