0
SELECT 
    `list_type`.`type`
FROM
    `events`
        INNER JOIN
    `list_type` ON `events`.`type` = `list_type`.`id`
WHERE
    `events`.`date` BETWEEN '2012-01-01' AND '2012-12-31'
        AND `events`.`center_id` = 2
GROUP BY `events`.`name`

Baseline
Baseline
Baseline
Baseline
Baseline
Baseline
Baseline
Special Events
Special Events
Special Events

But I would like it to count each type like this

Baseline    7
Special Events  3

so i tried this

SELECT 
    `list_type`.`type`,
    COUNT(*)
FROM
    `events`
        INNER JOIN
    `list_type` ON `events`.`type` = `list_type`.`id`
WHERE
    `events`.`date` BETWEEN '2012-01-01' AND '2012-12-31'
        AND `events`.`center_id` = 2
GROUP BY `events`.`name`

But it gives me this:

Baseline    45
Baseline    3
Baseline    56
Baseline    23
Baseline    12
Baseline    9
Baseline    2
Special Events  5
Special Events  4
Special Events  18

It is counting the number of each name and type not the output form query. I also tried COUNT(list_type.type) Thanks for your help.

1
  • Have you tried count(distinct list_type.type) Commented Jan 28, 2013 at 16:00

3 Answers 3

1

You can always count the result of your query using a subquery, like this:

SELECT type, count(*)
FROM (
  ...your query above...
) s
GROUP BY type

it will surely work, but it's not necessarily the best way to proceed. I think you should just group by list_type.type:

GROUP BY list_type.type

and then you have to count distinct events name for every type, like this:

SELECT 
    `list_type`.`type`,
    COUNT(DISTINCT `events`.`name`)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks that worked. I did this in the past but did not add the "s" after the ) so it did not work.
@user1658688 you're welcome! MySql requires that you give an alias to all subqueryes, I used just s that stands for subquery, but you can use something more descriptive like groupedEvents or anything you like
@user1658688 pls don't forget to accept the answer if you find it useful :) tnx
0

GROUPed then by list_type.type

SELECT  list_type.type,
        COUNT(*) totalCount
FROM    events
        INNER JOIN list_type 
            ON events.type = list_type.id
WHERE   events.date BETWEEN '2012-01-01' AND '2012-12-31'
        AND events.center_id = 2
GROUP   BY list_type.type

Comments

0

Don't group by events.name

Try grouping by list_type.type

Since you were grouping by event, then it was giving you results and numbers based on events!

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.