【问题标题】:query to check if records exists in both or either of 2 columns查询以检查记录是否存在于两列或两列中
【发布时间】:2020-04-05 16:01:51
【问题描述】:

我有一张表,我需要比较 2 列。请参见下面的示例: 我需要查询我应该将第 1 列和第 2 列分组并告诉 ABC = XYZ = 123,按日期分组并获得数量总和。

我尝试查询我使用比较(column1 = column2 或column2 = column1)并使用按日期分组。但是我没有得到预期的结果。

任何帮助将不胜感激。

编辑: 添加了示例数据和预期结果。我期待第 1 行和第 2 行相同的答案,因为第 2 列匹配的数据在第 1 列中找到。

【问题讨论】:

  • 发布示例数据和预期结果并更好地解释您的要求。
  • 添加的数据和有问题的预期结果

标签: mysql database


【解决方案1】:

我尝试为您的预期结果创建选择,但是会为忽略行设置一些语句,这些语句已更改:

SELECT col1, col2, done_at, SUM(qty) FROM (
    SELECT col1, col2, done_at, qty, 0 AS semiline
        FROM test WHERE 1

UNION ALL

    SELECT test1.col2 AS col1, test1.col1 AS col2, test1.done_at, test1.qty, 1 AS semiline
        FROM test AS test1
        JOIN test AS test2 ON test1.col2=test2.col1
        WHERE 1 GROUP BY test1.col2, test1.col1, test1.done_at

) AS result WHERE 1
GROUP BY col1, done_at;

+------+------+------------+----------+
| col1 | col2 | done_at    | SUM(qty) |
+------+------+------------+----------+
| ABC  | XYZ  | 2017-12-29 |        2 | <-- this row is bad, i think...
| XYZ  | 123  | 2017-12-29 |        3 |
| XYZ  | 123  | 2018-10-04 |        7 |
+------+------+------------+----------+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多