子查询返回多个值sql查询错误

时间:2016-01-12 07:54:49

标签: sql sql-server

我有以下代码。我从此查询中获得Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. 。请查看下面的查询。

SELECT X.ITEMCODE,
       X.[ITEM_DESCRIPTION],
       X.[Received],
       X.[Issues],
       X.[Project]
FROM (
    SELECT DISTINCT
        T0.ItemCode AS ITEMCODE,
        T0.ItemName AS [ITEM_DESCRIPTION],
        ISNULL((
            SELECT SUM(T1.[Quantity])
            FROM IGN1 T1
            WHERE T1.[DocDate] BETWEEN '1march2015' AND '1march2015'
                AND T1.WhsCode = 'RecBay'
                AND T1.[ItemCode] = T0.[ItemCode]
        ), 0) AS [Received],
        ISNULL((
            SELECT T1.[Project]
            FROM IGN1 T1
            WHERE T1.[DocDate] BETWEEN '1march2015' AND '1march2015'
                AND T1.WhsCode = 'RecBay'
                AND T1.[ItemCode] = T0.[ItemCode]
        ), 0) AS [Project],
        ISNULL((
            SELECT SUM(CAST(T1.[Quantity] AS INT))
            FROM IGE1 T1
            WHERE T1.DocDate BETWEEN '1march2015' AND '1march2015'
                AND T1.WhsCode = 'RecBay'
                AND T1.[ItemCode] = T0.[ItemCode]
        ), 0) AS [Issues]

    FROM OITM T0
) X

3 个答案:

答案 0 :(得分:2)

您可以尝试以下查询,让我知道您获得的错误:

;WITH CTE AS
(
    SELECT
        T0.ItemCode AS ItemCode,
        ISNULL(SUM(T1.[Quantity]),0) AS Received,
        ISNULL(T1.[Project], '') AS Project,
        SUM(CAST(T1.[Quantity] AS INT)) AS Issues
    FROM OITM T0
    LEFT JOIN IGN1 T1 ON T1.[ItemCode] = T0.[ItemCode]
    WHERE T1.[DocDate] BETWEEN '1march2015' AND '1march2015'
        AND T1.WhsCode = 'RecBay'
)
SELECT DISTINCT
    T0.ItemCode AS ITEMCODE,
    T0.ItemName AS [ITEM_DESCRIPTION],
    T1.*
FROM OITM T0
LEFT JOIN CTE T1 ON T1.ItemCode = T0.ItemCode

答案 1 :(得分:0)

尝试这样的事情 -

SELECT DISTINCT
    T0.ItemCode AS ITEMCODE,
    T0.ItemName AS [ITEM_DESCRIPTION],
    ISNULL([Received], 0) AS [Received],
    ISNULL([Project], '') AS [Project],
    ISNULL([Issues], 0) AS [Issues]
FROM OITM T0
OUTER APPLY (
    SELECT
          [Issues] = SUM(CAST(T1.[Quantity] AS INT))
        , [Received] = SUM(T1.[Quantity])
        , [Project] = MAX(T1.[Project])
    FROM IGN1 T1
    WHERE T1.[DocDate] BETWEEN '1march2015' AND '1march2015'
        AND T1.WhsCode = 'RecBay'
        AND T1.[ItemCode] = T0.[ItemCode]
) T1

并提供数据集的一个小例子

答案 2 :(得分:0)

我可以从您的查询中获取一些信息,我可以说OITM的项目代码与IGN1的项目不是1对1。这就是你的错误的原因,问题是你想要的是什么样的结果。 我可以做这样的事情:

$('#text-edit').Editor('setText',<p>test month</p>);

如果这是您想要的,您可以将您的子查询转为左连接

    ======================================================
    ItemCode   ItemName   Received    Project    Issues  
    ======================================================
      1           a          c        Unknown     1008
      1           a          c        Unknown1    1008
      1           a          c        Unknown2    1087