SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 How to make query using sqlserver
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

qasimidl
Starting Member

Pakistan
10 Posts

Posted - 03/27/2012 :  05:14:02  Show Profile  Reply with Quote
i have to make query

My table structure is like this

towncodeNo TownName

2023001 M1
2023001 M1
2031025 Z1
2031025 Z1
2031030 Z1

Result should be

Townname TotalTown
M1 1
Z1 2

Kindly help me to make query using SQLServer 05

GilaMonster
Flowing Fount of Yak Knowledge

South Africa
4507 Posts

Posted - 03/27/2012 :  05:23:56  Show Profile  Visit GilaMonster's Homepage  Reply with Quote
Look up COUNT DISTINCT

--
Gail Shaw
SQL Server MVP
Go to Top of Page

qasimidl
Starting Member

Pakistan
10 Posts

Posted - 03/27/2012 :  07:25:29  Show Profile  Reply with Quote
I have solved

solution

select t.townname,count(distinct(t.towncode)) from town t
group by t.townname,t.towncode
Go to Top of Page

GilaMonster
Flowing Fount of Yak Knowledge

South Africa
4507 Posts

Posted - 03/27/2012 :  08:08:48  Show Profile  Visit GilaMonster's Homepage  Reply with Quote
That won't work.

That will give you:
M1 1
Z1 1
Z1 1

You want to group by the town name, not both the name and code. You almost never want to group by a column you are aggregating, just doesn't make sense to do so.

--
Gail Shaw
SQL Server MVP
Go to Top of Page

qasimidl
Starting Member

Pakistan
10 Posts

Posted - 03/27/2012 :  14:47:59  Show Profile  Reply with Quote
select t.townname,count(distinct(t.towncode))as total from town t
group by t.townname


101percent its working
thanks

quote:
Originally posted by GilaMonster

That won't work.

That will give you:
M1 1
Z1 1
Z1 1

You want to group by the town name, not both the name and code. You almost never want to group by a column you are aggregating, just doesn't make sense to do so.

--
Gail Shaw
SQL Server MVP


Edited by - qasimidl on 03/27/2012 14:54:19
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.12 seconds. Powered By: Snitz Forums 2000