2

myTable

Basically I have a table name myTable and inside has Name,Class , I would like to sort them out like the table below with a count of each name and number of 1,2,3s they have.Below is the codes I currently had but it work on small amount of entries, if the table has 20,000 lines it took a very long time to execute.

Select DISTINT(Name),
       (Select count(*) from `myTable` d1 where d1.Name = dd.Name and Class=1),
       (Select count(*) from `myTable` d2 where d2.Name = dd.Name and Class=2),
       (Select count(*) from `myTable` d3 where d3.Name = dd.Name and Class=3)
from `myTable` dd
Order by Name;

3 Answers 3

2

It is classic conditional aggregation:

Select Name,
       sum(case when Class = 1 then 1 else 0 end),
       sum(case when Class = 2 then 1 else 0 end),
       sum(case when Class = 3 then 1 else 0 end)
from myTable
group by Name
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your efficient answer, the query time for 50,000 entries is so much faster now.
0

You can pivot it:

SELECT t.Name,
    SUM(if(t.Class=1,1,null)) as Class1,
    SUM(if(t.Class=2,1,null)) as Class2,
    SUM(if(t.Class=3,1,null)) as Class3
FROM myTable t
GROUP BY t.Name

Comments

0

Do a GROUP BY with conditional counting:

select Name,
       count(case when class = 1 then 1 end),
       count(case when class = 2 then 1 end),
       count(case when class = 3 then 1 end)
from `myTable`
group by Name;

Note: DISTINCT is not a function on a column, it works on the whole selected rows. (It doesn't matter if the column-name is put within parentheses or not.)

select distinct(col1), col2, ...

is the same as

select distinct col1, col2, ...

and also the same as

select distinct col1, (col2), ...

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.