Reputation: 173
I have sql query like that:
SELECT
CONCAT(t1.a, t2.a, t2.b, t3.a, t4.a, t4.b) AS val
FROM
t1
LEFT JOIN t2 ON ...
LEFT JOIN t3 ON ...
LEFT JOIN t4 ON ...
val output as: 0,1,0,1,2,1 OR 1,2,0,1,0,2,... (includes 0,1,2 in random order)
I want count total for each number, as: 0=>2, 1=>3, 2=>1, without PHP code
Upvotes: 0
Views: 39
Reputation: 180887
You could simply wrap your existing query in a subquery, and make an outer query that counts the occurrences;
SELECT
LENGTH(val) - LENGTH(REPLACE(val, '0', '')) zeros,
LENGTH(val) - LENGTH(REPLACE(val, '1', '')) ones,
LENGTH(val) - LENGTH(REPLACE(val, '2', '')) twos
FROM (
SELECT
CONCAT(t1.a, t2.a, t2.b, t3.a, t4.a, t4.b) AS val
FROM
t1
LEFT JOIN t2 ON ...
LEFT JOIN t3 ON ...
LEFT JOIN t4 ON ...
);
Upvotes: 1
Reputation: 2245
You need to use UNION ALL
for this.
SELECT tbl.col1, COUNT(tbl.col1)
FROM (
SELECT t1.a as col1
FROM t1
UNION ALL
SELECT t2.a as col1
FROM t2
UNION ALL
SELECT t3.a as col1
FROM t3
...
) tbl
GROUP BY tbl.col1;
Upvotes: 0