SQL Server : return most frequently occurring values (and counts) from across 9 columns in one table -


i have sql server 2005 database table (expenseformitems) (among other things) stores street addresses across 11 columns (fromtravel, totravel, totravel1, totravel2, totravel3....totravel9).

basically trip 11 total legs/stops, google calculated mileage/etc (not important here).

i able return (say 15) occurring addresses across 11 columns, number of times occur.

so basically

[to]             [occurrances] ============== address1               328 address2               233 address3               112 .... address15               23 

i'm guessing sort of un/pivot in use here, i've never done cool enough have used 1 before, not grasping how apply (what i've read them) case.

tia

it sounds want unpivot data take data columns , convert rows.

the basic structure be:

select col, address expenseformitems unpivot (   address   col in (fromtravel, totravel, totravel1,               totravel2, totravel3, totravel4,               totravel5, totravel6, totravel7,                totravel8, totravel9) ) unpiv 

then if want find number of occurrences, can use:

select address, count(address) occurrences (   select col, address   expenseformitems   unpivot   (     address     col in (fromtravel, totravel, totravel1,                 totravel2, totravel3, totravel4,                 totravel5, totravel6, totravel7,                  totravel8, totravel9)   ) unpiv ) d group address  order occurrences desc; 

if wanted return 15 frequent addresses, add top 15 select.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -