SQL 查询以下内容
SQL query for the below
Table A 有当前 ValueA
和 ValueB
:
Token ValueA ValueB
ABC SHOP Val1
DEF SHOP Val2
GHI SHIPP Val3
JKL SHIPP Val2
Table B 有所有的数据转换:
Token Value Value2 Date Express
ABC SHOP Val1 2020-01-01 Yes
ABC. SHOP Val2 2020-02-01 Yes
ABC SHIPP. Val3 2020-03-01 Yes
DEF SHOP Val1 2020-05-01 No
DEF SHIPP Val2 2020-04-01 No
DEF SHIPP. Val3 2020-03-01 No
我希望我的结果应该包括来自 TableA 的最新数据,但添加来自 TableB 的特定日期:
Token ValueA Val1 Date Val2 Date
ABC SHOP . 2020-01-01 2020-02-01
DEF SHOP 2020-05-01. 2020-04-01
GHI SHIPP NULL NULL
JKL SHIPP NULL NULL
我的查询没有返回我预期的结果:
SELECT a.token,
A.valueA,
A.valueB,
B.Express
c.Date "SHOP DATE",
d.Date “SHIP DATE"
FROM TableA A
LEFT JOIN TABLEB B ON A.Token = B.Token
LEFT JOIN TABLEB C ON A.Token = B.Token
LEFT JOIN TABLEB D ON A.Token = B.Token
WHERE (c.value = ‘SHOP’ AND c.value2 = ‘Val1’)
AND (c.value = ‘SHIP’ AND c.value2 = ‘Val13)
GROUP BY a.token
ORDER BY b.date DESC;
查询结果:
Token ValueA Val1 Date Val2 Date
ABC SHOP . 2020-01-01 2020-02-01
DEF SHOP 2020-05-01. 2020-04-01
将WHERE
条件移入JOIN
:
SELECT a.token,
A.valueA,
A.valueB,
B.Express
c.Date "SHOP DATE",
d.Date "SHIP DATE"
FROM TableA A
LEFT JOIN TABLEB B
ON A.Token = B.Token
LEFT JOIN TABLEB C
ON A.Token = B.Token
AND c.value = 'SHOP' AND c.value2 = 'Val1'
AND c.value = 'SHIP' AND c.value2 = 'Val3'
LEFT JOIN TABLEB D
ON A.Token = B.Token
GROUP BY a.token
ORDER BY b.date DESC;
Table A 有当前 ValueA
和 ValueB
:
Token ValueA ValueB
ABC SHOP Val1
DEF SHOP Val2
GHI SHIPP Val3
JKL SHIPP Val2
Table B 有所有的数据转换:
Token Value Value2 Date Express
ABC SHOP Val1 2020-01-01 Yes
ABC. SHOP Val2 2020-02-01 Yes
ABC SHIPP. Val3 2020-03-01 Yes
DEF SHOP Val1 2020-05-01 No
DEF SHIPP Val2 2020-04-01 No
DEF SHIPP. Val3 2020-03-01 No
我希望我的结果应该包括来自 TableA 的最新数据,但添加来自 TableB 的特定日期:
Token ValueA Val1 Date Val2 Date
ABC SHOP . 2020-01-01 2020-02-01
DEF SHOP 2020-05-01. 2020-04-01
GHI SHIPP NULL NULL
JKL SHIPP NULL NULL
我的查询没有返回我预期的结果:
SELECT a.token,
A.valueA,
A.valueB,
B.Express
c.Date "SHOP DATE",
d.Date “SHIP DATE"
FROM TableA A
LEFT JOIN TABLEB B ON A.Token = B.Token
LEFT JOIN TABLEB C ON A.Token = B.Token
LEFT JOIN TABLEB D ON A.Token = B.Token
WHERE (c.value = ‘SHOP’ AND c.value2 = ‘Val1’)
AND (c.value = ‘SHIP’ AND c.value2 = ‘Val13)
GROUP BY a.token
ORDER BY b.date DESC;
查询结果:
Token ValueA Val1 Date Val2 Date
ABC SHOP . 2020-01-01 2020-02-01
DEF SHOP 2020-05-01. 2020-04-01
将WHERE
条件移入JOIN
:
SELECT a.token,
A.valueA,
A.valueB,
B.Express
c.Date "SHOP DATE",
d.Date "SHIP DATE"
FROM TableA A
LEFT JOIN TABLEB B
ON A.Token = B.Token
LEFT JOIN TABLEB C
ON A.Token = B.Token
AND c.value = 'SHOP' AND c.value2 = 'Val1'
AND c.value = 'SHIP' AND c.value2 = 'Val3'
LEFT JOIN TABLEB D
ON A.Token = B.Token
GROUP BY a.token
ORDER BY b.date DESC;