Friday, April 30, 2010

Recently I had a very non trivial situation where I had to display the max value in multiple columns of a table.I will like to illustrate a very simple example
Suppose I have a table with 3 columns namely color1,color2,color3 with different color values in all the column.My task is to display the color which is the most repeating in all the three columns for each id.With the below table structure and data the o/p for id 1 should be 'red' and for id 2 should be 'green'

So here is the query on how to do it.

declare @tbl as table(id int,color1 varchar(40),color2 varchar(40),color3 varchar(40))
insert into @tbl
select 1,'red','red','blue' union all
select 2,'green','red','green'

select T2.id,T1.color1,T1.color2,T1.color3,T2.col as MaxColor from @tbl T1 inner join
(
select *,ROW_NUMBER()over(PARTITION by id order by id )as rid from
(select * from @tbl)u
unpivot
(col for columns in (color1,color2,color3))v
)T2 on T1.id=T2.id where T2.rid=1

The trick here is to use unpivot & then by using ranking function assign an id which has the maximum number of color values for each distinct id & selecting the colors having rowid as 1.

Saturday, February 6, 2010

Sort on Alphanumeric values

I have seen so many post where developers face problem in sorting the data on alphanumeric values.The most simpls way to do is to use Isnumeric function (applicable for SQL 2005 and beyond).
Here is one of the solutions.

Declare @tbl as table(id int identity(1,1),value varchar(10))
insert into @tbl
select '123AS' union all
select '1245' union all
select 'ABC123AS' union all
select 'WE123AS' union all
select 'AS123AS' union all
select '123AS' union all
select '1'

select * from @tbl
order by isnumeric(value)desc,len(value)

The order will be descending on pure numeric values .

If you need it to be ascending then simply use

select * from @tbl
order by isnumeric(value),len(value) desc

My name is Sachin Nandanwar. I like to think I speak for the average developer. Here's a few facts about me:

  • My current focus is in Microsoft .NET, primarily in Web development using ASP.NET but currently putting more of my effort into database developement.
  • My database of choice is SQL Server 2005 & 2008. I also know Microsoft Access very well and have dabbled in MySQL. The first database I used on the PC was R:Base.
  • I program in both C# and VB. I also programmed in VB 6.0 and JavaScript.
  • I dont beleive in degrees because they hardly teach you anything practical in life.But still I have a bachelors degree in Mathematcis. I was born in Amchi Mumbai.
  • The only website I really really love to haunt is www.sqlteam.com.
  • Like body building & was a fitness trainer before fully concentrating into IT.
  • I am married to a beautiful wife
  • If God willing hope to write a book on Database Development and become a SQL Server MVP.

Thanks for reading my blog.

Sachin Nandanwar