0

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

1
  • What exactly do you want to know? I don't know what to say more, I think it's totally cleared. I want to count display times on each of value: 0,1,2 Commented Feb 3, 2016 at 5:14

2 Answers 2

1

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 ...
);
Sign up to request clarification or add additional context in comments.

Comments

0

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;

SQLFIDDLE DEMO

1 Comment

It's a good solution, but I think Joachim's solution is better. Thanks anyway!

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.