23.8.08

Distinct filename or distinct items in SQL Server

Distinct filename or distinct items in SQL Server
Let see some interesting facts like identifying the unique file types available in the database.
Considering, I have stored lot of file types in my database and I need to find, what are the filetypes available
in my database.
---Created a sample table
Create Table VenkatTable (fname varchar(50))
Insert into VenkatTable values('1.doc')
Insert into VenkatTable values('2.doc')
Insert into VenkatTable values('3.doc')
Insert into VenkatTable values('1.xls')
Insert into VenkatTable values('2.xls')
Insert into VenkatTable values('3.xls')
Insert into VenkatTable values('4.xls')
Method 1:
Select Count(*) as [Count],right(fname,3) as FileType from VenkatTable
group by right(fname,3) Order by [Count] desc

Here am trying to use "right" method to fetch the file types availabel in my db. But, this method will fail
if the length of the file extension is more than or less than 3. In that case, we can prefer the second method.
If we are pretty much sure that the extension is of length 3. Method 2:
select
distinct substring (fname, charindex('.',fname)+1,len(fname)) as filetype,
count(*) as count from VenkatTable
group by substring (fname, charindex('.',fname)+1,len(fname))
Its a very generic method to identify all filetypes available in our db.
Happy Learning!!!
Regards,
Venkatesan Prabu .J

2 comments:

  1. nice one. thankx for this blog. i want to R &D on ur blog

    ReplyDelete
  2. Your are always welcome....

    Regards,
    Venkatesan Prabu .J

    ReplyDelete