Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: SQL-server-2005
Here is my table structure
ID   Name      Phone_No 
1    ABC        123
2    ABC        123
3    XYZ        222
4    PQR       444
 
and required output is like this; Here is i want to add another colunm which gives count as per Phone No
 
ID   Name      Phone_No   Count
1    ABC        123         2
2    ABC        123         2
3    XYZ        222         1
4    PQR        444         1
 
So plz help me how to write sql query
Posted 10-Jan-13 2:19am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Try this one:
select t1.ID, t1.Name, t1.Phone_No, (select count(*) from mytable t2 where t2.Name=t1.Name and t2.Phone_No=t1.Phone_No) as Count from mytable t1
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Select T1.ID, T1.Name, T1.Phone_no, T2.Count From myTable T1, (Select Phone_no, Count(Phone_No) as Count From myTable) as T2 Where T1.Phone_no = T2.Phone_no
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Hi,
 
you can first make the Scalar valued function which returns the count.
 
CREATE FUNCTION fn_GetPhoneCount 
(
	@Phone_No nvarchar(50) = ''
)
RETURNS int
AS
BEGIN
 
	Declare @Cnt INT
	SET @Cnt = 0
 
	Select @Cnt = COUNT(*) from Table_1 where Phone_No = @Phone_No
 
	Return @Cnt
END
 
Then write the query like this.
 
Select [ID], [Name], [Phone_No], dbo.fn_GetPhoneCount([Phone_No]) AS [Count] from Table_1
 
I hope this will help you to get your answer.
  Permalink  
Comments
AshishSarang at 11-Jan-13 5:35am
   
Thanks...!!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

Look at here ... How do u like that...Smile | :)
SELECT T11.ID , T11.Name , T11.Phone_No , COUNT(T11.Phone_No)  FROM T11 (NOLOCK)
INNER JOIN T11 as B (NOLOCK)
    ON B.Name = T11.Name
GROUP BY T11.ID , T11.Name , T11.Phone_No
Regards,
Vijay
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

Try this:
 
Select ID,Name,Phone_no, Count(Phone_no)
From TableName
GroupBy ID,Name,Phone_no
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 543
1 OriginalGriff 384
2 George Jonsson 258
3 Abdul Samad KP 135
4 Animesh Datta 130
0 OriginalGriff 6,099
1 Sergey Alexandrovich Kryukov 5,411
2 CPallini 4,770
3 George Jonsson 3,400
4 Gihan Liyanage 2,522


Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 14 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100