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
 General SQL Server Forums
 New to SQL Server Programming
 ORDER BY

Author  Topic 

sambrown180
Starting Member

38 Posts

Posted - 2008-11-19 : 05:30:27
I am trying to run a query that will show a list of ID's with the ones that are repeated the most shown first. The ID is productID

What order by command could be used to do this?

I want the output to look like:

productID:
2
2
2
2
4
4
4
3
3
1

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-11-19 : 05:33:58
[code]DECLARE @Sample TABLE
(
i INT
)

INSERT @Sample
SELECT 2 UNION ALL
SELECT 2 UNION ALL
SELECT 2 UNION ALL
SELECT 2 UNION ALL
SELECT 4 UNION ALL
SELECT 4 UNION ALL
SELECT 4 UNION ALL
SELECT 3 UNION ALL
SELECT 3 UNION ALL
SELECT 1

SELECT i,
COUNT(*) OVER (PARTITION BY i)
FROM @Sample
ORDER BY COUNT(*) OVER (PARTITION BY i) DESC,
i[/code]


E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

sambrown180
Starting Member

38 Posts

Posted - 2008-11-19 : 05:41:10
Im sorry i really didnt understand that could you dumb it down a bit please

Sorry
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-11-19 : 05:42:13
How much down?



E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

sambrown180
Starting Member

38 Posts

Posted - 2008-11-19 : 05:44:19
is there not a simple code that will show the most repeated fields first
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-11-19 : 05:45:42
[code]SELECT t.*
FROM YourTable t
INNER JOIN (SELECT ProductID,COUNT(*) as reccnt
FROM YouRtable
GROUP BY ProductID)t1
ON t1.ProductID=t.ProductID
ORDER BY t1.reccnt DESC
[/code]
Go to Top of Page

sambrown180
Starting Member

38 Posts

Posted - 2008-11-19 : 05:49:16
That is fantastic worked a treat. Could you please explain hows this works for future reference.

Thanks
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-11-19 : 05:58:51
quote:
Originally posted by sambrown180

That is fantastic worked a treat. Could you please explain hows this works for future reference.

Thanks


you're taking each productid's number of occurances in the subquery (count() gives number of occurances). then you order it by decreasing order of count of occurances to get desired o/p.
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-11-19 : 05:59:22
quote:
Originally posted by sambrown180

is there not a simple code that will show the most repeated fields first
So you are not using SQL Server 2005?


E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

sambrown180
Starting Member

38 Posts

Posted - 2008-11-21 : 10:19:16
yes i am why?
Go to Top of Page
   

- Advertisement -