【问题标题】:How to use subquery to create new column如何使用子查询创建新列
【发布时间】:2022-01-04 03:37:27
【问题描述】:

我在查询某些信息时遇到了一些问题

select id_column, d_description
from table1
where (select substring(cast(g_xml_comprobante as nvarchar(max)), charindex('contrato=', cast(g_xml_comprobante as nvarchar(max))) + 10, 15) as 'contract' 
       from table1 a, table 3 b
       where convert(varchar(6), b.d_date, 112) > '202108' 
         and b.id_column = a.id_column) = '2019896177'

我收到此错误:

消息 512,第 16 级,状态 1,第 1 行
子查询返回超过 1 个值。当子查询跟随 =、!=、、>= 或子查询用作表达式时,这是不允许的。

情况是这样的,我们在table1的一列中有XML信息,在XML中我们有一个合同号。所以我想要的是从某些合同中获取所有的 ID,我有合同的价值,这就是为什么我需要它在哪里。

有可能实现吗?

如果我不清楚,请告诉我,以便我澄清。

感谢您的帮助!

【问题讨论】:

标签: sql sql-server xml subquery


【解决方案1】:

您正在尝试将子查询结果与常量进行比较。 但是您的子查询返回多个值。 在这种情况下,您可以在子查询之前使用 ANY 或 ALL。 ANY 表示如果任何返回值符合条件,则结果为真。 ALL 表示如果所有返回值都符合条件,则结果为真。

【讨论】:

    【解决方案2】:

    Serge 写的也是对的。 但是,如果您只是检查子查询中是否存在特定的合同 ID,并且由于某种原因,多行具有相同的合同,那么您可以做的是。 您可以使用 In 子句如下

    select id_column, d_description
    from table1
    where '2019896177' in (select substring(CAST(g_xml_comprobante as nvarchar(max)),CHARINDEX('contrato=',CAST(g_xml_comprobante as nvarchar(max)))+10,15) as 'contract' from table1 a,table3 b
    where convert(varchar(6),b.d_date,112) > '202108' and b.id_column=a.id_column
    )
    

    但是第二种方法在处理此类错误时很常见,但这主要取决于您的数据,返回的数据是什么。 如果您的子查询为所有行返回相同的值,那么最好的方法是在您的子查询中使用Top 1

    select id_column, d_description
    from table1
    where (select Top 1 substring(CAST(g_xml_comprobante as nvarchar(max)),CHARINDEX('contrato=',CAST(g_xml_comprobante as nvarchar(max)))+10,15) as 'contract' from table1 a,table3 b
    where convert(varchar(6),b.d_date,112) > '202108' and b.id_column=a.id_column
    )='2019896177'
    

    【讨论】:

      【解决方案3】:

      您的查询有很多问题:

      select
        t1.id_column,
        t1.d_description
      from table1 t1
      where exist (select 1
          from [table 3] t3
          where t3.d_date > '202108'
            and t3.id_column = t1.id_column
             -- not sure exactly what XQuery you are looking for
            and t3.g_xml_comprobante.exist('//@contrato[. = "2019896177"]') = 1
      );
      

      【讨论】:

        猜你喜欢
        • 2020-08-27
        • 1970-01-01
        • 2015-01-19
        • 2019-10-01
        • 1970-01-01
        • 2021-10-25
        • 2021-09-26
        • 1970-01-01
        • 2021-07-29
        相关资源
        最近更新 更多