Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting values in columns

What I am looking for is to group by and count the total of different data in the same table and have them show in two different columns. Like below.

Data in table A

Fields:

Name    Type  
 Bob    1  
 John   2 
 Bob    1 
 Steve  1 
 John   1 
 Bob    2

Desired result from query:

Name   Type 1  Type 2
Bob    2       1
John   1       1
Steve  1       0
like image 307
Adam Smith Avatar asked May 10 '26 17:05

Adam Smith


2 Answers

This will do the trick in SQL Server:

SELECT
  name,
  SUM( CASE type WHEN 1 THEN 1 ELSE 0 END) AS type1,
  SUM( CASE type WHEN 2 THEN 1 ELSE 0 END) AS type2
FROM
  myTable
GROUP BY
  name
like image 112
Seb Avatar answered May 12 '26 06:05

Seb


No time to write the code, but the Case statement is what you want here. SImply havea value of 1 if it meets the case and zero if it deosn't. Then you can sum the columns.

like image 43
HLGEM Avatar answered May 12 '26 08:05

HLGEM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!