gpt4 book ai didi

VLOOKUP 的 SQL 版本

转载 作者:行者123 更新时间:2023-12-04 17:48:43 32 4
gpt4 key购买 nike

我是 SQL 新手,如果您有空闲时间,我想知道是否有人可以帮我在 SQL 中复制 Excel Vlookup 函数?

从一些研究中,我怀疑它是我需要的 join 函数之一,但是,我不想只选择包含在两个表中的数据 - 我只想在 1 个表中查找另一个表中的值。

如果数据包含在查找表中,则返回值,如果没有,则返回 NULL

我在下面给出了几个示例表来帮助说明我的问题。

请注意产品 'C' 和 'D' 不在表 2 中,但它们仍在结果表中,但值为 NULL。

此外,我有大量独特的产品,所以我不是在寻找包含硬编码的答案,例如; CASE WHEN [Product] = 'A' THEN...
表1

Product    Quantity
-------------------
A 10
B 41
D 2
C 5
B 16
A 19
C 17
A 21

表 2
Product    Cost
-----------------
A £31.45
B £97.23

结果表
Product   Quantity    Cost
-----------------------------
A 10 £31.45
B 41 £97.23
D 2 NULL
C 5 NULL
B 16 £97.23
A 19 £31.45
C 17 NULL
A 21 £31.45

最佳答案

看起来好像你需要一个外连接,我将在我的例子中使用一个左连接:

select t1.Product, t1.Quantity, t2.Cost
from table1 as t1
left outer join table2 as t2
on t1.Product = t2.Product

您还可以省略外部关键字:
select t1.Product, t1.Quantity, t2.Cost
from table1 as t1
left join table2 as t2
on t1.Product = t2.Product

关于VLOOKUP 的 SQL 版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24104707/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com