創建表/插入數據
CREATE TABLE Table1
(`date` VARCHAR(7), `ID` INT, `amount1` INT, `amount2` INT)
;
INSERT INTO Table1
(`date`, `ID`, `amount1`, `amount2`)
VALUES
('11-2-16', 2, 2, 0),
('11-2-16', 1, 5, 11),
('11-2-16', 3, 0, 9),
('12-2-16', 2, 4, 0),
('12-2-16', 1, 4, 0)
;
CREATE TABLE Table2
(`Bdate` VARCHAR(7), `BID` INT, `Bamount1` INT, `Bamount2` INT)
;
INSERT INTO Table2
(`Bdate`, `BID`, `Bamount1`, `Bamount2`)
VALUES
('11-2-16', 1, 5, 11),
('11-2-16', 2, 1, 0),
('11-2-16', 3, 0, 6),
('12-2-16', 1, 4, 0),
('12-2-16', 2, 1, 0)
;
查詢
加入日期和id並使用哪裏來過濾出字段不匹配的地方。
SELECT
Table1.date AS "Date"
, Table1.id
, (CASE WHEN Table1.Amount1 > 0 THEN Table1.Amount1 ELSE NULL END) AS "Amount1"
, (CASE WHEN Table2.Bamount1 > 0 THEN Table2.Bamount1 ELSE NULL END) AS "Bamount1"
, (CASE WHEN Table1.amount2 > 0 THEN Table1.amount2 ELSE NULL END) AS "amount2"
, (CASE WHEN Table2.Bamount2 > 0 THEN Table2.Bamount2 ELSE NULL END) AS "Bamount2"
FROM
Table1
INNER JOIN
Table2
ON
Table1.date = Table2.Bdate
AND
Table1.id = Table2.Bid
WHERE
Table1.amount1 != Table2.Bamount1
OR
Table1.amount2 != Table2.Bamount2
結果
Date id Amount1 Bamount1 amount2 Bamount2
------- ------ ------- -------- ------- ----------
11-2-16 2 2 1 (NULL) (NULL)
11-2-16 3 (NULL) (NULL) 9 6
12-2-16 2 4 1 (NULL) (NULL)
請詳細說明 「這是不匹配」。目前尚不清楚你的意思 – apomene
不符合數據可以在金額1或金額2 –