5

I have a sql select query that extracts result as:

login_count  login_type
2000         iPhone
7000         browser 

But i want the result as:

iphone_login  browser_login
2000          7000

i.e. i want to extract row1-col1 as col1 and row2-col2 as col2 using a select query.

My original query is

select count(login_count), login_type from log_table group by login_type;

Thanks, Gaurav

2 Answers 2

3

Try this:

SELECT
    SUM( IF(login_type = 'iPhone', 1, 0) ) AS iphone_login,
    SUM( IF(login_type = 'browser', 1, 0) ) AS browser_login
FROM log_table
Sign up to request clarification or add additional context in comments.

2 Comments

Incidentally, how many times have you given this answer? That isn't meant as a criticism, it just seems like I see at least one new "select rows as columns" question every single day. We need some kind of community-wide close-as-duplicate binge... If we could agree on which of these questions has the best 'canonical' answers... :)
@Eray Then use the original query and let Excel transpose the types into columns for you. ;)
0

Here is another option that works in MySQL and in other dbms as well.

select sum(case when login_type = 'iPhone'  then 1 else 0 end) as iphone_login
      ,sum(case when login_type = 'browser' then 1 else 0 end) as browser_login
from log_table   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.