snippetsqlModerate
How to use COUNT with multiple columns?
Viewed 0 times
columnswithmultiplehowcountuse
Problem
How to use multiple columns with a single COUNT?
Assume that there is a table
I want to find the count of all the combination of user and book name.
I have tried that if i run with
However, when i remove
Question is how to use
Assume that there is a table
demo with these data: id | col1 | col2 |
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
1 |'alice' | 'book1'|
2 |'bob' | 'book1'|
3 |'alice' | 'book2'|
4 |'alice' | 'book3'|I want to find the count of all the combination of user and book name.
I have tried that if i run with
distinct, everything is alright.select count(distinct col1, col2) from demoHowever, when i remove
distinct, then the sql statement will not be passed in mysql console.select count(col1, col2) from demoQuestion is how to use
COUNT with multiple columns in MySql?Solution
There are several things you can count with
Tested at SQLfiddle:
But
gives an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
COUNT() function:count(*): rows
count(col1): rows wherecol1is not null
count(col2): rows wherecol2is not null
count(distinct col1): distinctcol1values.
count(distinct col2): distinctcol2values.
count(distinct col1, col2): distinct(col1, col2)values combinations.
Tested at SQLfiddle:
select
count(*) as count_rows,
count(col1) as count_1,
count(col2) as count_2,
count(distinct col1) as count_distinct_1,
count(distinct col2) as count_distinct_2,
count(distinct col1, col2) as count_distinct_1_2
from demo ;But
count(col1, col2) is not valid syntax:select
count(col1, col2)
from demo ;gives an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
'col2) from demo' at line 2.Code Snippets
select
count(*) as count_rows,
count(col1) as count_1,
count(col2) as count_2,
count(distinct col1) as count_distinct_1,
count(distinct col2) as count_distinct_2,
count(distinct col1, col2) as count_distinct_1_2
from demo ;select
count(col1, col2)
from demo ;Context
StackExchange Database Administrators Q#127564, answer score: 17
Revisions (0)
No revisions yet.