2012-07-25 118 views
0

時,這是不允許的我有下面的腳本由於標題中的錯誤而停止工作。有人可以提供一些幫助嗎?子查詢返回多個值。當子查詢如下

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 
+0

請下次正確格式化您的SQL查詢 – LittleBobbyTables 2012-07-25 12:59:34

+0

第一次使用。我如何正確格式化? – 2012-07-25 13:00:32

+0

選擇塊並點擊 K – wildplasser 2012-07-25 13:01:32

回答

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子句。

+0

這似乎工作。我不再收到錯誤,並且我的整個查詢正在運行。謝謝 – 2012-07-25 13:50:08

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 

此查詢返回的任何行都應指出問題出在哪裏。

+0

嗨,我運行你提供的查詢,它返回零行。 – 2012-07-25 13:16:03

+0

那裏有某種重複。嘗試運行沒有子查詢的原始腳本來驗證錯誤發生在何處,或嘗試在沒有Current_Read_Date分組的情況下運行我的查詢。如果視圖足夠小,請嘗試以可視方式進行檢查,您可能會注意到有問題的值。 – SWeko 2012-07-25 13:18:35

+0

我運行沒有Current_Read_Date分組的查詢並返回2518行。 – 2012-07-25 13:28:18