如何根据子查询的结果更改字段之一,错误:子查询返回的值超过1?

时间:2019-03-20 18:12:53

标签: sql sql-server subquery

我想做的是一个查询,该查询指示在表中找到的项目,并且一旦您拥有此类项目,这些项目的平均费率就是,通过另一个查询,我可以将百分比乘以该项目应存在于另一个表中的字段。

select CASE
    WHEN estimador.Clave = 'Perfiles' THEN (select gasto.[Importe Banco]*0.5 from SN_INT_PartidasGasto as gasto where gasto.[Clase de Coste]='FSW' and estimador.IdProyecto=gasto.[ID Proyecto] and AmbientePRE='PRE')
    WHEN estimador.Clave = 'Puntos V1' THEN 'Puntos V1'
    WHEN estimador.Clave = 'Puntos V2' THEN 'Puntos V2'
    ELSE 'Sorry, no match.'
    END AS CATEGORIA from tb_Estimador as estimador where estimador.IdProyecto in (select gse.FolioSantec from db_Incurrido.dbo.GSE_Real as gse where gse.FolioSantec=estimador.IdProyecto and estimador.Clave!='Tarifa Promedio')

在上面的查询中,出现以下错误:

Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= ,
>, >= or when the subquery is used as an expression.

2 个答案:

答案 0 :(得分:2)

选择部分的

子查询返回多于1行。您应该在其中添加top 1

select CASE
    WHEN estimador.Clave = 'Perfiles' THEN (select TOP 1 gasto.[Importe Banco]*0.5 from SN_INT_PartidasGasto as gasto where gasto.[Clase de Coste]='FSW' and estimador.IdProyecto=gasto.[ID Proyecto] and AmbientePRE='PRE')
    WHEN estimador.Clave = 'Puntos V1' THEN 'Puntos V1'
    WHEN estimador.Clave = 'Puntos V2' THEN 'Puntos V2'
    ELSE 'Sorry, no match.'
    END AS CATEGORIA from tb_Estimador as estimador where estimador.IdProyecto 
    in (select gse.FolioSantec from db_Incurrido.dbo.GSE_Real as gse where gse.FolioSantec=estimador.IdProyecto and estimador.Clave!='Tarifa Promedio')

答案 1 :(得分:0)

您可以将APPLYJOIN一起使用:

SELECT (CASE WHEN estimador.Clave = 'Perfiles' 
             THEN gasto.[Importe Banco] * 0.5
             WHEN estimador.Clave = 'Puntos V1' 
             THEN 'Puntos V1'
             WHEN estimador.Clave = 'Puntos V2' 
             THEN 'Puntos V2' 
             ELSE 'Sorry, no match.'
        END) AS CATEGORIA 
FROM tb_Estimador as estimador INNER JOIN
     db_Incurrido.dbo.GSE_Real AS gse
     ON gse.FolioSantec = estimador.IdProyecto OUTER APPLY
     (SELECT TOP (1) gasto.[Importe Banco] 
      FROM SN_INT_PartidasGasto AS gasto 
      WHERE gasto.[Clase de Coste] = 'FSW' AND 
            estimador.IdProyecto = gasto.[ID Proyecto] AND 
            AmbientePRE = 'PRE'
     ) gasto 
WHERE estimador.Clave <> 'Tarifa Promedio';