返回子查询的SQL查询返回了多个值错误

时间:2015-12-20 12:10:36

标签: sql sql-server

我有以下查询。请看看第一个

select 
    X.ITEMCODE, X.[ITEM_DESCRIPTION], X.[OPENING_BALANCE],   
    X.[SALES], X.[TOTAL_REJECTS], x.[REJECTION_DISEASES]
    (X.[SALES] - X.[TOTAL_REJECTS]) as [PRODUCTION_TOTAL], 
    X. [DOCDATE],
    (X.[OPENING_BALANCE] + (X.[SALES]-X.[TOTAL_REJECTS])) AS [CLOSING_BALANCE]
from
    (SELECT DISTINCT 
         T0.ItemCode AS ITEMCODE, T0.ItemName AS [ITEM_DESCRIPTION],
         ISNULL((SELECT SUM(T1.OnHand)  
                 FROM OITW T1 
                 WHERE T1.WhsCode = 'FGS' 
                   AND T1.ItemCode = T0.ItemCode), 0) AS [OPENING_BALANCE],
         ISNULL((SELECT SUM(T1.[Quantity]) 
                 FROM INV1 T1 
                 WHERE T0.[ItemCode] = T1.[ItemCode]), 0) AS [SALES] , 
         (SELECT T1.[DocDate] FROM INV1 T1 
          WHERE T0.[ItemCode] = T1.[ItemCode]) AS [DOCDATE],
         ISNULL((SELECT SUM(cast(T1.[Quantity] as int))  
                 FROM IGE1 T1 
                 WHERE T0.[ItemCode] = T1.[ItemCode]), 0) AS [TOTAL_REJECTS],
         ISNULL((SELECT T1.[U_RejectionOthers]   
                 FROM IGE1 T1 
                 WHERE T0.[ItemCode] = T1.[ItemCode]), 0) AS [REJECTION_DISEASES]
    from 
        OITM T0 
    where 
        T0.[ItmsGrpCod] in ('104', '121', '122', '123', '124', '125', '126', '127', '129', '130', '134', '135', '136', '139', '140', '141', '142', '143', '144', '145')) X
WHERE 
    X.[OPENING_BALANCE] > 0 OR X.[TOTAL_REJECTS] > 0  OR X.[SALES] > 0

在此代码中,当我尝试在主select语句中添加X.[DOCDATE]x.[REJECTION_DISEASES]时,我收到以下错误

  

子查询返回的值超过1。这是不允许的   子查询跟随=,!=,<,< =,>,> =或当子查询用作   表达。

请专家帮帮我。

1 个答案:

答案 0 :(得分:2)

我怀疑在sub-query子句中给定条件下面where下面会返回多行

Isnull((SELECT T1.[u_rejectionothers] 
        FROM   ige1 T1 
        WHERE  T0.[itemcode] = T1.[itemcode]), 0) AS[REJECTION_DISEASES] 

您需要修复where子句以返回一行,或TOPOrder by以返回一行

修复where条款。将所有条件放在where子句中,通过该子句可以在ige1

中标识唯一行
Isnull((SELECT T1.[u_rejectionothers] 
        FROM   ige1 T1 
        WHERE  T0.[itemcode] = T1.[itemcode]
          AND  T1.somecol  = 'XXX'), 0) AS[ REJECTION_DISEASES] 

TOP

中添加Order bysub-query
Isnull((SELECT TOP 1 T1.[u_rejectionothers] 
        FROM   ige1 T1 
        WHERE  T0.[itemcode] = T1.[itemcode]
        Order by somecol), 0) AS [REJECTION_DISEASES]