0

I have trouble wondering how do I count distinct value. using if on the select column

I have SQLFIDDLE here

http://sqlfiddle.com/#!2/6bfb9/3

Records shows:

create table team_record (
  id tinyint,
  project_id int,
  position varchar(45)
  );

insert into team_record values
(1,1, 'Junior1'),
(2,1, 'Junior1'),
(3,1, 'Junior2'),
(4,1, 'Junior3'),
(5,1, 'Senior1'),
(6,1, 'Senior1'),
(8,1, 'Senior2'),
(9,1, 'Senior2'),
(10,1,'Senior3'),
(11,1, 'Senior3'),
(12,1, 'Senior3')

I need to count all distinct value, between Junior and Senior column.

all same value would count as 1.

I need to see result something like this.

PROJECT_ID  SENIOR_TOTAL    JUNIOR_TOTAL
1                3              3

mysql query is this. but this is not a query to get the result above.

SELECT 
    `team_record`.`project_id`,
    `position`,       
    SUM(IF(position LIKE 'Senior%',
        1,
        0)) AS `Senior_Total`,
    SUM(IF(position LIKE 'Junior%',
        1,
        0)) AS `Junior_Total`
FROM
    (`team_record`)        
WHERE
    project_id = '1'        
GROUP BY `team_record`.`project_id`

maybe you could help me fix my query above to get the result I need.

thanks

1
  • This would be much simpler (and faster) if you separated the numeric component out to another column Commented Sep 3, 2014 at 7:12

1 Answer 1

6

I think you want this:

SELECT 
   project_id,
   COUNT(DISTINCT CASE when position LIKE 'Senior%' THEN position END) Senior_Total,
   COUNT(DISTINCT CASE when position LIKE 'Junior%' THEN position END) Junior_Total
FROM team_record
WHERE project_id = 1
GROUP BY project_id

The CASE will return a null if the WHEN is false (ie ELSE NULL is the default, which I omitted for brevity), and nulls aren't counted in DISTINCT.

Also, unnecessary back ticks, brackets and qualification removed.

Sign up to request clarification or add additional context in comments.

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.