[英]SQL Server INNER JOIN with two tables
I have two tables TableA
and TableB
like this: 我有两个这样的表
TableA
和TableB
:
TableA
ItemCode |Qty |BarCode |Brand
AC |2 |123 |BRO
AB |2 |1234 |BRO
AD |2 |1234 |BRO
TableB
ItemCode |Brand |BarCode |Qty
AC |BRO |123 |1
AB |BRO |1234 |2
I trying to get the result like Records TableA
not equal to Qty of TableB
and records in TableA
is not in TbleB
我试图得到类似Records
TableA
的结果不等于TableB
数量,并且TableA
记录不在TbleB
The query I have tried is 我尝试过的查询是
SELECT
A.ItemCode AS ItmA, B.ItemCode AS ItmB, A.Qty AS AQty, B.Qty AS BQty
FROM
TableA A
INNER JOIN
TableB B ON A.Brand = B.Brand
WHERE
(A.Qty <> B.Qty)
AND A.ItemCode NOT IN (B.ItemCode)
I am getting result like this 我得到这样的结果
ItmA |ItmB |AQty |BQty
--------------------------------
AB | AC | 2 | 1
AD | AC | 2 | 1
But I am trying to get the result with ItemCode AC
AND AD
但是我正在尝试使用ItemCode
AC
和AD
获得结果
If you want to get records from TableA
that are not in TableB
, then think LEFT OUTER JOIN
: 如果要从
TableA
获取不在TableB
,请考虑LEFT OUTER JOIN
:
SELECT A.ItemCode AS ItmA,B.ItemCode AS ItmB,A.Qty AS AQty,B.Qty AS BQty
FROM TableA A LEFT JOIN
TableB B
ON A.Brand = B.Brand
WHERE A.Qty <> B.Qty OR B.Brand IS NULL;
The rest is just applying the logic of your query. 其余的只是应用查询的逻辑。
You can also express this as: 您也可以这样表示:
SELECT A.ItemCode AS ItmA,B.ItemCode AS ItmB,A.Qty AS AQty,B.Qty AS BQty
FROM TableA A LEFT JOIN
TableB B
ON A.Brand = B.Brand AND A.Qty = B.Qty
WHERE B.Brand IS NULL;
But I think the first version comes close to how you expressed the rules. 但是我认为第一个版本与您表达规则的方式很接近。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.