2

I´d like to count a value which exists in 2 different tables. But it should be displayed seperated like this:

enter image description here

Of course I can count it seperately. But I want to have it in one query in one result. Thanks for your help

SELECT `X1`, COUNT(`X1`) AS Sales FROM `table1` GROUP BY `X1`

SELECT `X1`, COUNT(`X1`) AS Purchases FROM `table2` GROUP BY `X1`
Barmar
  • 741,623
  • 53
  • 500
  • 612
Wakan
  • 53
  • 3

2 Answers2

1

This is a pain, because the set of x1 values in each table may not be the same.

Here is one approach using union all and group by:

select x1, sum(sales) as sales, sum(purchases) as purchases
from ((select x1, count(*) as sales, 0 as purchases
       from table1
       group by x1
      ) union all
      (select x2, 0, count(*)
       from table2
       group by x1
      )
     ) t12
group by x1;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Use a subquery to get the counts from one of the tables, and then join that with the other table.

SELECT t1.x1, COUNT(*) AS sales, t2.purchases
FROM table1 AS t1
JOIN (SELECT x1, COUNT(*) AS purchases
       FROM table2
       GROUP BY x1) AS t2
ON t1.x1 = t2.x1
GROUP BY t1.x1

It might actually be more efficient to do the grouping in two subqueries.

SELECT t1.x1, t1.sales, t2.purchases
FROM (SELECT x1, COUNT(*) AS sales
      FROM table1
      GROUP BY x1) AS t1
JOIN (SELECT x1, COUNT(*) AS purchases
      FROM table2
      GROUP BY x1) AS t2
ON t1.x1 = t2.x1

However, if there are any x1 values that aren't in both tables, both these queries will leave them out. The ideal solution is FULL OUTER JOIN, but MySQL doesn't have this operation. See Full Outer Join in MySQL for a workaround. Gordon Linoff's answer doesn't have this problem. Or if you have another table that lists all the x1 values, you could use that as the main table, and LEFT JOIN both of the above subqueries with it.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612