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.
| 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 productIDWhat order by command could be used to do this?I want the output to look like:productID:2222444331 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2008-11-19 : 05:33:58
|
[code]DECLARE @Sample TABLE ( i INT )INSERT @SampleSELECT 2 UNION ALLSELECT 2 UNION ALLSELECT 2 UNION ALLSELECT 2 UNION ALLSELECT 4 UNION ALLSELECT 4 UNION ALLSELECT 4 UNION ALLSELECT 3 UNION ALLSELECT 3 UNION ALLSELECT 1SELECT i, COUNT(*) OVER (PARTITION BY i)FROM @SampleORDER BY COUNT(*) OVER (PARTITION BY i) DESC, i[/code] E 12°55'05.63"N 56°04'39.26" |
 |
|
|
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 pleaseSorry |
 |
|
|
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" |
 |
|
|
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 |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-11-19 : 05:45:42
|
| [code]SELECT t.*FROM YourTable tINNER JOIN (SELECT ProductID,COUNT(*) as reccnt FROM YouRtable GROUP BY ProductID)t1ON t1.ProductID=t.ProductIDORDER BY t1.reccnt DESC[/code] |
 |
|
|
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 |
 |
|
|
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. |
 |
|
|
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" |
 |
|
|
sambrown180
Starting Member
38 Posts |
Posted - 2008-11-21 : 10:19:16
|
| yes i am why? |
 |
|
|
|
|
|