I have the following script which has stopped working due the error in the title. Could someone please provide some assistance?
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
The problem would seem to be the subquery in the 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)
This is returning too many rows. Perhaps you want to change it to:
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)
Since you use the same subquery twice, you should really put it in the FROM clause.
As far as I can see, you have this subquery in your script
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)
If this returns a single value (one column in one record), than it will be included in your result, however, if this returns more than one row, you'll get the error you're getting.
Take a look at the data in the Vw_Level_3_Sales_This_Year view to see if there are duplicates per lLocationID / Current_Read_Date, since those are the fields you are filtering by. Something along the lines of:
SELECT count(*), lLocationID, Current_Read_Date
FROM dbo.Vw_Level_3_Sales_This_Year
GROUP BY lLocationID, Current_Read_Date
HAVING count(*)>1
Any rows returned by this query should indicate where the problem is.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.