I am trying to count in multiple columns then group by for a total sum where the same data appears in any column
Source data table:
P1 P2 P3
-----------
a b
a a a
b c
a b b
b a
I want it to show something like this:
Desired query output:
Total
-------------
a | 6
b | 5
c | 1
The GROUP BY clause is used along with some aggregate functions to group columns with the same values in different rows. The group by multiple columns technique retrieves grouped column values from one or more database tables by considering more than one column as grouping criteria.
The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.
Yes, it is possible to use MySQL GROUP BY clause with multiple columns just as we can use MySQL DISTINCT clause.
You can use CASE statement to count two different columns in a single query. To understand the concept, let us first create a table. The query to create a table is as follows. Insert some records in the table using insert command.
You can use a union query
SELECT x.f1,Count(x.f1) FROM
(SELECT p1 As F1 FROM table
UNION ALL
SELECT p2 As F1 FROM table
UNION ALL
SELECT p3 As F1 FROM table) x
GROUP BY x.f1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With