求和,计数和分组时的MYSQL乘法结果

时间:2019-05-19 17:06:50

标签: mysql

我认为我需要一些帮助。现在尝试了百万次不同的查询,但没有任何效果。我希望它求和t1.a并计数t2.b并显示结果,但它会将两者相乘。

我尝试过左联接,右联接,无联接,但是我认为我没有解决此问题的技能!

$query ="SELECT t1.date, t1.a, t2.date, t2.b,
     SUM(t1.a) AS sum1,
     COUNT(t2.b) AS sum2
     FROM t1
     LEFT JOIN t2
     ON t1.date = t2.date
     GROUP BY t1.date, t2.date
     ";

t1:

id date        a
1  2019-05-01  5
2  2019-05-01  5
3  2019-05-01  5
4  2019-05-01  1
5  2019-05-01  1
6  2019-05-02  5
7  2019-05-02  5
8  2019-05-02  5

t2:

id date        b
1  2019-05-01  d
2  2019-05-01  d
3  2019-05-01  d
4  2019-05-02  d
5  2019-05-02  d
6  2019-05-02  d
7  2019-05-02  d
8  2019-05-02  d

结果是:

2019-05-01  51  15
2019-05-02  75  15

但是应该是:

2019-05-01  17  3
2019-05-02  15  5

我做错了什么?

1 个答案:

答案 0 :(得分:-1)

根据您的预期结果,必须首先将每个表分组,然后将它们联接:

SELECT 
  t1.date, t1.sum1, t2.sum2
FROM (
  SELECT t1.date, SUM(t1.a) AS sum1
  FROM t1 GROUP BY t1.date
) t1 LEFT JOIN (
  SELECT t2.date, COUNT(t2.b) AS sum2
  FROM t2 GROUP BY t2.date
) t2
ON t1.date = t2.date

请参见demo
结果:

| date       | sum1 | sum2 |
| ---------- | ---- | ---- |
| 2019-05-01 | 17   | 3    |
| 2019-05-02 | 15   | 5    |