【问题标题】:Left Join Sum not returning expected values左连接总和未返回预期值
【发布时间】:2020-11-25 19:15:50
【问题描述】:

我有 2 个要加入的表,但查询有时会在另一行匹配。

表 t1

+-----+
| Re  |
+-----+
| 123 |
| 321 |
+-----+

表table2

+-----+-----+-----+-----+
| Re  | Re2 | Cla | Val |
+-----+-----+-----+-----+
| 123 | abc | RV  |  10 |
| 123 | cba | AB  |   5 |
| 321 | xyz | ZV  |   4 |
| 321 | zyx | RV  |   6 |
+-----+-----+-----+-----+

查询

 select t1.Re,t2.Re2, sum(t2.Importeenmonedalocal) as Sum, from table t1
 left join table2 as t2 on
 t2.Re LIKE CONCAT('%',t1.Re,'%') 
 group by t1.Re;

实际结果:

+-----+-----+-----+
| Re  | Re2 | Sum |
+-----+-----+-----+
| 123 | cba |  15 |
| 321 | xyz |  10 |
+-----+-----+-----+

预期结果:

Cla='RV' 像这样时,我期望的是 t2 中的连接匹配:

+-----+-----+-----+
| Re  | Re2 | Sum |
+-----+-----+-----+
| 123 | abc |  15 |
| 321 | zyx |  10 |
+-----+-----+-----+

我尝试像这样添加where

 select t1.Re,t2.Re2, sum(t2.Importeenmonedalocal) as Sum, from table t1
 left join   table2 as t2  on
 t2.Re  LIKE CONCAT ('%',t1.Re,'%') 
 where t2.Cla='RV'
 group by t1.Re;

但总和不正确:

+-----+-----+-----+
| Re  | Re2 | Sum |
+-----+-----+-----+
| 123 | abc |  10 |
| 321 | zyx |   6 |
+-----+-----+-----+

知道如何进行这项工作吗?

【问题讨论】:

  • 我正在使用这个查询来连接表这个查询是不确定的。例如 - 在第一个输出行中 t2.Re2 有时可能是 'abc',有时是 'cba'..

标签: mysql


【解决方案1】:
SELECT t1.Re,
       MAX( CASE WHEN t2.Cla='RV' THEN t2.Re2 END ) Re2,
       SUM( t2.Importeenmonedalocal ) `Sum`
FROM `table` t1
LEFT JOIN table2 t2 ON t2.Re LIKE CONCAT ('%',t1.Re,'%') 
GROUP BY t1.Re;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    相关资源
    最近更新 更多