Question

i have different mobile types in a table. Types like iPhone,android,windows etc. I want to get the individual counts of each type using the same query. I used the below query to get count of one type.

   `select type,
    count(1) AS total
    from mobile_types where type = 'iPhone'
    group by type;'

I got the required o/p using this for one record.

iPhone 1000

But when i try it for multiple records i am getting an error. I used the following for multiple records.

   'select type,
    count(1) AS total
    from mobile_types where type = 'iPhone'
    from mobile_types where type = 'windows'
    group by type;'

the error i got was "ParseException line 5:0 missing EOF at 'from' near ''iPhone''"

And is there a way to get the output in below format,with types as column names and the count below as row?

|iPhone|windows|android|

1000 |1500 |900 |

UPDATE

I was able to get the individual counts using the below script.

'select type,
    count(1) AS total
    from mobile_types where type = 'iPhone' OR type = 'android' OR type = 'windows'
    group by type;'

But still need above mentioned o/p format. Current o/p format

iphone 1000

android 900

windows 1500.

Any suggestions?

Was it helpful?

Solution

To get the output format you're looking for:

select
sum(if(type = 'iphone', 1, 0)) as n_iphone,
sum(if(type = 'android', 1, 0)) as n_android,
sum(if(type = 'windows', 1, 0)) as n_windows
from mobile_types;

OTHER TIPS

You don't need the where clause to get the type. This will show a list of all types with the count of each in the total column.

select type,
count(*) AS total
from mobile_types 
group by type;

AFTER COMMENT

SELECT type,
COUNT(*) AS total
FROM mobile_types 
WHERE type IN ('IPhone','Android', 'Other Phone Names')
GROUP BY type;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top