Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join select statements to get columns in SQL

Tags:

sql

t-sql

SELECT COUNT(Type) from House where Type = 1
SELECT COUNT(Type) from House where Type = 2
SELECT COUNT(Type) from House where Type = 3

My question is: I want to join the above 3 statements to get: 3 columns i.e. eg: ColumnType1: '50', ColumnType2: '60', columnType3: '45'

thanks

like image 215
Moh Najdawi Avatar asked Jan 17 '26 05:01

Moh Najdawi


1 Answers

You can create the columns using an aggregate function with a CASE expression:

SELECT 
  count(case when Type = 1 then Type end) as type_1,
  count(case when Type = 2 then Type end) as type_2,
  count(case when Type = 3 then Type end) as type_3
from House
like image 196
Taryn Avatar answered Jan 19 '26 18:01

Taryn



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!