表A
> - Product#|Customer|state|Type
Glasses |mr. Xyz | MN |Instore
Glasses |mr. abc | MN |Instore
perishables|mr. abc12| TN |Instore
N-perishables|mr. abc122| GN |Instore
表B
> - Product#|Name|state|Type
Glasses |mr. fff | MN |online
Glasses |mr. abc | MN |online
perishables|mr. abc12 | TN |online
Non-perishables|mr. abc122 | GN |online
`
尝试创建新列,然后进行比较?条件是,如果类型为店内,则它们永远不是新客户;如果在线,则只有在店内类型中不存在记录的情况下,他们才可以为新客户。
o / p
Type|customer| New Customer?
Instore|mr. Xyz |No
Instore|mr. abc |No
Instore|mr. abc12|No
Instore|mr. abc122|No
Online| mr.fff |Yes -"as it's record is not available in-store type, hence it will be labelled as new customer"
尝试查询:
select
`Customer`,
CASE
WHEN `customer` in (select `Customer` from `Table B`) THEN 'Yes'
ELSE 'NO'
END AS 'new customer'
FROM Table A`
答案 0 :(得分:0)
使用连接而不是子查询:
SELECT
COALESCE(a."Type", b."Type") as type,
COALESCE(a."Customer", b."Name") as customer,
CASE
WHEN b."Type" = 'online' AND a."Customer" IS NULL THEN 'Yes'
ELSE 'No'
END AS new_customer
FROM "Table_B" b
FULL JOIN "Table_A" a
ON a."Customer" = b."Name";
顺便说一句,两个表中的数据似乎都是重复的,您可能需要重新考虑自己的模式。
答案 1 :(得分:0)
您可以将LEFT
和RIGHT
联接与UNION
结合使用:
SELECT coalesce(type_a ,type_b) as type,
coalesce(customer_a,customer_b) as customer,
case when type_a is null then 'Yes' else 'No' end as New_Customer
FROM
(
SELECT a.type as type_a,a.customer as customer_a,
b.type as type_b,b.customer as customer_b
FROM TableA a
LEFT JOIN TableB b
ON a.Customer=b.Customer
UNION
SELECT a.type as type_a,a.customer as customer_a,
b.type as type_b,b.customer as customer_b
FROM TableA a
RIGHT JOIN TableB b
ON a.Customer=b.Customer
) q
答案 2 :(得分:0)
您需要一个LEFT JOIN
中的一个TableB
到TableA
和一个CASE
表达式,它们将返回您想要的结果:
select
b.Product,
case when a.Product is null then 'YES' else 'NO' end as `new customer`
from TableB as b left join TableA as a
on b.Product = a.Product
请参见demo。
结果:
| Product | new customer |
| ------- | ------------ |
| 11120 | NO |
| 11121 | NO |
| 11122 | NO |
| 11123 | NO |
| 11124 | YES |