子查询返回的值超过1。当子查询跟随时,不允许这样做

时间:2012-07-25 12:58:05

标签: sql

我有以下脚本由于标题中的错误而停止工作。有人可以提供一些帮助吗?

SELECT DISTINCT TOP 100 PERCENT
         Locs.lCustomerGroupPK, Locs.lCustomerID, Locs.Customer_Group_Name, Locs.Customer_Name, Locs.Location_Name, TY.ThisYearsSales,
        (SELECT ThisYearsSales
           FROM dbo.Vw_Level_3_Sales_This_Year
          WHERE (lLocationID = Locs.lLocationID2 OR lLocationID = Locs.llocationid)
            AND (Current_Read_Date = TY.Current_Read_Date - 364) AND (ThisYearsSales <= 400)
         ) AS LastYearsSales, 
         TY.Current_Read_Date - 1 AS Current_Read_Date INTO #tmplocationlflsales
  FROM dbo.Vw_Level_3_Sales_This_Year AS TY 
        INNER JOIN dbo.vw_locations_Like_For_Like_Previous AS Locs 
                ON TY.lLocationID = Locs.llocationid OR TY.lLocationID = Locs.lLocationID2
 WHERE (TY.ThisYearsSales <= 400)
    AND (TY.Current_Read_Date = @RecordDate)
    AND TY.ThisYearsSales IS NOT NULL
    AND (SELECT ThisYearsSales
           FROM dbo.Vw_Level_3_Sales_This_Year
          WHERE (lLocationID = Locs.lLocationID2 OR lLocationID = Locs.llocationid) 
            AND (Current_Read_Date = TY.Current_Read_Date - 364) 
            AND (ThisYearsSales <= 400)
         ) IS NOT NULL 
 ORDER BY Locs.Customer_Group_Name, Locs.Customer_Name, Locs.Location_Name, Current_Read_Date

2 个答案:

答案 0 :(得分:0)

问题似乎是SELECT中的子查询:

        SELECT ThisYearsSales
        FROM dbo.Vw_Level_3_Sales_This_Year
        WHERE (lLocationID = Locs.lLocationID2 OR 
                lLocationID = Locs.llocationid) 
            AND (Current_Read_Date = TY.Current_Read_Date - 364) 
            AND (ThisYearsSales <= 400)

这会返回太多行。也许您想将其更改为:

        SELECT sum(ThisYearsSales)
        FROM dbo.Vw_Level_3_Sales_This_Year
        WHERE (lLocationID = Locs.lLocationID2 OR 
                lLocationID = Locs.llocationid) 
            AND (Current_Read_Date = TY.Current_Read_Date - 364) 
            AND (ThisYearsSales <= 400)

由于您使用相同的子查询两次,因此您应该将它放在FROM子句中。

答案 1 :(得分:0)

据我所知,你的脚本中有这个子查询

SELECT ThisYearsSales
FROM dbo.Vw_Level_3_Sales_This_Year
WHERE (lLocationID = Locs.lLocationID2 OR lLocationID = Locs.llocationid) 
 AND (Current_Read_Date = TY.Current_Read_Date - 364) 
 AND (ThisYearsSales <= 400)

如果这返回单个值(一个记录中的一列),那么它将包含在结果中,但是,如果这返回多行,您将收到错误。

查看Vw_Level_3_Sales_This_Year视图中的数据,查看每个lLocationID / Current_Read_Date是否有重复项,因为这些是您要过滤的字段。有点像:

SELECT count(*), lLocationID, Current_Read_Date 
FROM dbo.Vw_Level_3_Sales_This_Year
GROUP BY lLocationID, Current_Read_Date 
HAVING count(*)>1

此查询返回的任何行都应指出问题所在。