0

I have a table named Users. I am trying out to grab some data from it with the following query:

select name, lastname, gender, status, count(status = 'Trvl') as TrvlCount,
       count(status != 'Trvl') as NotTrvlCount, count(id) as TotalCount
from Users
group by name, lastname, gender, dob;

The expected result would be 7 columns with unique name, lastname,gender, dob (to avoid duplicates) and sum of different statuses. But I cant rectify why all 3 count columns are showing the same value or same sum value?

Any idea guys? Thanks in advance.

3
  • The general GROUP BY rule is: "If a GROUP BY clause is specified, each column reference in the SELECT list must either identify a grouping column or be the argument of a set function." I.e. I'd try group by name, lastname, gender, status. Commented Apr 26, 2016 at 8:42
  • but still i get the same result jarlh Commented Apr 26, 2016 at 8:46
  • COUNT will just count rows, try SUM instead if you're trying to count how many rows match those conditions (it works just because TRUE equals 1 and FALSE equals 0) Commented Apr 26, 2016 at 8:49

2 Answers 2

2

You should use sum if construction:

select name, lastname, gender, status, 
       sum(if(status = 'Trvl',  1, 0)) as TrvlCount,
       sum(if(status != 'Trvl',  1, 0)) as NotTrvlCount,
       count(id) as TotalCount
from Users
group by name, lastname, gender, dob;
Sign up to request clarification or add additional context in comments.

Comments

0
select name, lastname, gender, status, 
       (SELECT COUNT() FROM Users WHERE status = 'Trvl') as TrvlCount,
       (SELECT COUNT() FROM Users WHERE status <> 'Trvl') as NotTrvlCount,
       count(id) as TotalCount
from Users
group by name, lastname, gender, dob;

Also you can do it with subqueries.

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.