Click here to Skip to main content
15,908,115 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi for exmple this table
HTML
id        name       code     
 1        test       20
 2        test2      30  
 3        test       20
 4        test3      40
 5        test       20
 6        test       20

i want this result 
 id       name      code       count
  1       test       20          4
Posted
Updated 28-Jan-15 7:45am
v2
Comments
Kornfeld Eliyahu Peter 28-Jan-15 14:09pm    
Look for group by...

Use the group by and COUNT.

SQL
SELECT MIN(id) AS id, name, code, COUNT(*) AS count_of_name
FROM table
GROUP BY id, name, code


Richard brought up a good point that I overlooked. You cannot have the ID in your result set if you want the count because you are counting name and code, not id, name, and code.

I updated the sql so that you'll get the lowest ID for each name and code combination.

Update:

Kornfeld also brings up a good point. Even though you put ID in the result set, there's a good chance you don't actually want that in your result set and it's just the numbering of rows in the UI.

Then just remove ID from the sql and you'll have:
SQL
SELECT name, code, COUNT(*) AS count_of_name
FROM table
GROUP BY name, code


But for us to know for sure, we need to hear some feedback from you.
 
Share this answer
 
v3
Comments
Richard Deeming 28-Jan-15 14:21pm    
Based on the question, I suspect the OP wants to group by name and code, and take the minimum id.

He possibly also wants to filter the results to those records with more than one entry, since "test2" and "test3" don't appear in the result.
ZurdoDev 28-Jan-15 14:31pm    
Good call. I didn't pay close attention to the ID. I'll update solution.
Kornfeld Eliyahu Peter 28-Jan-15 14:32pm    
Sorry, but wrong answer...
It will give you 4 rows as id can not be grouped (all different values)...
I think new id has nothing to do with old id - it's a simple row-counter...
ZurdoDev 28-Jan-15 14:34pm    
Probably right. Richard just pointed that out. I had overlooked it. I updated solution.
Kornfeld Eliyahu Peter 28-Jan-15 14:37pm    
Perfect!
Hi Here is your query.

SQL
SELECT MIN(id) AS id, name, code, COUNT(*) AS [Count]
FROM MyTable
GROUP BY  name, code


Please mark as answer.

Thanks,
Vipul
 
Share this answer
 
Comments
Vipul J Patel 30-Jan-15 6:50am    
Why you have given minus rating? The answer is correct as per your question. Please explain.
SQL
iam wriet this code
 

SELECT code, COUNT (code)
FROM table GROUP BY code
HAVING COUNT (code)=
(
SELECT MAX (mycount)
FROM (
SELECT code, COUNT (code) mycount
FROM table
GROUP BY code
)tt
)
 
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