【问题标题】:SQL - Get value of column for rows matching a string AND a list of strings not found in the table?SQL - 获取与字符串匹配的行的列值和表中未找到的字符串列表?
【发布时间】:2021-02-17 17:44:44
【问题描述】:

我有一个表(除其他外)有一个“序列号”(VARCHAR(50)) 列和一个“活动”(BOOLEAN) 列...所以数据示例可能如下所示:

serial       | active
-------------+-------
ABCD232010E5 | True
ABCD1820102C | False
ABCD1820102C | True
ZYXW06210F20 | True
ABCD402004EZ | False

现在,从外部来源,我得到了一个序列号列表,如下所示:

ABCD232010E5
ZYXW49201X20
ABCD1820102C
ABCD402004EZ
ZYXW012100R3
ABCD44200B1W

是否可以运行一个(理想情况下)查询或一系列查询来获取以下详细信息:

  • 序列号是否有active=True 条目?
  • 如果没有,是否有 active=False 条目?
  • 如果表中根本不存在,请明确列出

我对输出不是很挑剔,只要:

  • 我输入的所有连续剧都列出了,无论它们是否存在
  • 我输入的每个序列仅列出一次,无论它在表中出现多少次
  • 如果表中存在,是否至少有一个条目有active=True

类似下面的就可以了(添加了 cmets 来解释我为什么期望给定的输出):

serial       | exists | active
-------------+--------+-------
ABCD232010E5 | True   | True    --has one record with active=True
ZYXW49201X20 | False  | False   --serial not found in table
ABCD1820102C | True   | True    --has one record with active=True and 1+ with active=False
ABCD402004EZ | True   | False   --only has record(s) with active=False
ZYXW012100R3 | False  | False   --serial not found in table
ABCD44200B1W | False  | False   --serial not found in table

如果输出只有两列也可以,active= 用于表中不存在的序列号。正如我所说的我不挑剔,我只需要能够区分三种状态(存在且有active=True,存在且没有active=True,不存在)。

【问题讨论】:

    标签: sql postgresql select


    【解决方案1】:

    一种方法是子查询:

    select i.*,
           (exists (select 1 from serials s where s.serial = i.serial and active
           )) as has_active_true,
           (exists (select 1 from serials s where s.serial = i.serial and not_active
           )) as has_active_false,
           (not exists (select 1 from serials s where s.serial = i.serial
           )) as no_match
    from input i;
    

    这可以通过将末尾的 input i 替换为以下内容直接针对值列表运行:

    (VALUES
            ('serial1'),('serial2'),('serial3'),
            ('serial4'),('serial5'),('serial6')
    ) AS i (serial)
    

    【讨论】:

    • 谢谢,这正是我想要的!子查询缺少第二个结束括号,所以我为此提交了一个编辑。它不允许我编辑,因为更改只有 3 个字符,所以我添加了如何查询值列表,因为这是我的特定用例,我认为它也可能对其他人有所帮助。
    猜你喜欢
    • 2013-06-18
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多