簡體   English   中英

查詢以檢查記錄是否存在於兩列或兩列中

[英]query to check if records exists in both or either of 2 columns

我有一張表,我需要比較 2 列。 請參見下面的示例:我需要查詢我應該將第 1 列和第 2 列分組並告訴 ABC = XYZ = 123,按日期分組並獲得數量總和。

我嘗試查詢我使用比較(column1 = column2 或column2 = column1)並使用按日期分組。 但是我沒有得到預期的結果。

任何幫助,將不勝感激。

在此處輸入圖像描述

編輯:添加示例數據和預期結果。 我期待第 1 行和第 2 行相同的答案,因為第 2 列匹配的數據在第 1 列中找到。

在此處輸入圖像描述

我嘗試為您的預期結果創建 select ,但是將為忽略行設置一些已更改的語句:

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 |
+------+------+------------+----------+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM