Click here to Skip to main content
15,920,603 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 3 column in a table each column 1 (CUT) and Column 2 (GROUP), column 3 (EmployeeID)
having entries like

age 15-20 GOOD  E_123
age 15-20 VGOOD E_128
age 15-20 VGOOD E_123
age 15-20 BAD   E_128
age 20-25 BAD   E_124
age 20-25 GOOD  E_126
age 20-25 VGOOD E_127
age 20-25 BAD   E_124
age 20-25 BAD   E_126
age 20-25 GOOD  E_127


I want out put like

col1  col2  col3  col4      col5
 age 15-20 GOOD    1         4
 age 15-20 VGOOD   2         4
 age 15-20 BAD     1         4
 age 20-25 GOOD    2         6
 age 20-25 VGOOD   1         6
 age 20-25 BAD     3         6


col4 is groupby EMPID
col5 is sum of group by for col2

[edit]Code block added - OriginalGriff[/edit]

What I have tried:

SQL
SELECT col1, col2, COUNT(EMPID) AS countempid
FROM table1 GROUP BY col1, col2 order by  AgeGroup,EngLevel
Posted
Updated 30-May-16 4:53am
v2

Try this:
C#
SELECT col1, col2, col3, count(col3) AS col4, 
(
  SELECT count(col2) FROM tablename t2 WHERE t2.col2=t1.col2
)
AS col5 FROM tablename t1
GROUP BY col1, col2, col3
 
Share this answer
 
v2
Comments
Maciej Los 30-May-16 14:19pm    
5ed!
Peter Leow 30-May-16 22:19pm    
Thank you, Maciej.
Rahul Yadav India 31-May-16 1:10am    
Thanks dear for the solution it worked..!
In addition to Solution 1 (I'm not personally a fan of correlated sub-queries)...

You can use (non-correlated) sub-queries in a JOIN ..
SQL
SELECT A.col1, A.col2, A.countempid, B.col5
FROM 
(	
	SELECT col1, col2, COUNT(EMPID) AS countempid
	FROM table1 GROUP BY col1, col2 
) A
INNER JOIN 
(	
	SELECT col1, COUNT(*) as col5 FROM table1 GROUP BY col1 
) B ON A.col1=B.col1
ORDER BY A.col1, A.col2

Or you could use Common Table Expressions[^]
SQL
;WITH CTE1 AS 
(
	SELECT col1, col2, COUNT(EMPID) AS countempid
	FROM table1 GROUP BY col1, col2 
), CTE2 AS
(
	SELECT col1, COUNT(*) as col5 FROM table1 GROUP BY col1 
)
SELECT C1.col1, C1.col2, C1.countempid, C2.col5
FROM CTE1 C1 
INNER JOIN CTE2 C2 ON C1.col1=C2.col1
ORDER BY C1.col1, C1.col2

Or my particular favourite using OVER clause[^]
SQL
SELECT DISTINCT col1, col2, COUNT(EMPID) OVER (PARTITION BY col1, col2) AS countempid,
COUNT(EMPID) OVER (PARTITION BY col1)
FROM table1 
ORDER BY col1, col2
 
Share this answer
 
Comments
Maciej Los 30-May-16 14:19pm    
+5!
CHill60 30-May-16 14:51pm    
Thank you!

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