Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL nested query possible?

Tags:

sql

nested

I have found select statements that basically use different where clauses to count. My question is, how do I combine the results in one statement so that these counts can become columns?

  1. select count(*) as c1 from table1 where city = 'nyc'
  2. select count(*) as c2 from table1 where city = 'boston'
  3. select count(*) as c3 from table1 where city = 'sf'
like image 240
Yang Avatar asked Nov 24 '25 14:11

Yang


2 Answers

SELECT
  COUNT(CASE WHEN city = 'nyc' THEN 1 END) AS Nyc,
  COUNT(CASE WHEN city = 'boston' THEN 1 END) AS Boston,
  COUNT(CASE WHEN city = 'sf' THEN 1 END) AS Sf
FROM table
like image 196
Michael Fredrickson Avatar answered Nov 27 '25 03:11

Michael Fredrickson


You can give GROUP BY a chance,

SELECT city, gender, count(*)
WHERE gender = "male"
GROUP BY city, gender;
like image 28
Mahmut Ali ÖZKURAN Avatar answered Nov 27 '25 04:11

Mahmut Ali ÖZKURAN



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!