0

I need query to get the count of participants in each level.

Note: participant who is in level 4 should not be in other levels ex: Level 3,2,1. I.e. I'm only interested in the highest level of each participant.

Table :

  +----+-------+----------+
  | ID | Level |  Date    |
  +----+-------+----------+
  | 38 | 1     |  06 -05  |
  | 38 | 2     |  08 -05  |
  | 38 | 3     |  12 -05  |
  | 38 | 4     |  13 -05  |
  | 39 | 1     |  13 -05  |
  | 39 | 2     |  13 -05  |
  | 40 | 1     |  12 -05  |
  +----+-------+----------+

Needed Output:

  +-------+-------+ 
  | Count | Level | 
  +-------+-------+ 
  | 1     | 1     |
  | 1     | 2     |
  | 0     | 3     |
  | 1     | 4     |
  +-------+-------+
4
  • 4
    how for level 3 you have 0 count with the given data ? Commented Jun 4, 2014 at 7:32
  • State Your expectaion clearly.... Commented Jun 4, 2014 at 7:33
  • participant ID 38 already existed in level 4 so that we consider only highest level Commented Jun 4, 2014 at 7:38
  • No participants is having highest level with 3 Commented Jun 4, 2014 at 7:40

3 Answers 3

2

Try this:

SELECT count(t2.Id) as count,t1.Level as level
FROM table1 t1
LEFT JOIN
(SELECT Id,MAX(Level) as Level
FROM table1
GROUP BY Id ) t2 on t1.Id=t2.Id and t1.Level=t2.Level
GROUP BY t1.Level

You can test it on SQL Fiddle

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

2 Comments

What are the efficiency constraints in this query?
If I understand your question correctly, the bottleneck, performance-wise is the join with the result set on the 2 fields.
0

I think you're looking for

Select Count(*), Level FROM table_name GROUP BY Level

1 Comment

In this query we count participant id 38 in all levels but we need count only in level 4
0

the expected result is to know how many people have a level as max level, grouping by level.

SELECT count(id) as count, level
FROM
(
  SELECT id, max(level) as level
  FROM myTable
  GROUP BY id
) t1
GROUP BY level;

1 Comment

This won't show the row where level is 3 and count is 0.

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.