Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

XML
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

Try this one:
SQL
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
 
Share this answer
 
Hi,

you can first make the Scalar valued function which returns the count.

SQL
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.

SQL
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.
 
Share this answer
 
Comments
AshishSarang 11-Jan-13 5:35am    
Thanks...!!
Look at here ... How do u like that...:)
SQL
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
 
Share this answer
 
v2
Try this:

Select ID,Name,Phone_no, Count(Phone_no)
From TableName
GroupBy ID,Name,Phone_no
 
Share this answer
 
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
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900