0

这是我要实现的存储过程:

    Alter PROCEDURE pro_worst_supplier_test 
@datey nvarchar(4), @datem nvarchar(2)
   AS
   BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here

select y.CompanyName from (SELECT s.CompanyName,(select min(t.b) from (select (round(sum(OD.Quantity * (1-OD.Discount) * OD.UnitPrice),0)) as b from [Order Details] group by ProductID) t) as q
FROM ((((Products p 
inner join [Order Details] OD on p.ProductID=OD.ProductID) 
inner join Categories c on p.CategoryID=c.CategoryID) 
inner join Suppliers s on p.SupplierID=s.SupplierID)
inner join Orders o on o.OrderID=od.OrderID)
where c.CategoryName='Produce' AND SUBSTRING(CONVERT(nvarchar(22), o.OrderDate, 111),1,4)=@datey AND SUBSTRING(CONVERT(nvarchar(22),o.OrderDate, 111),6,2)=@datem
group by s.CompanyName) y
where q=(select MIN(q)from y) 
END 
GO

当我试图通过

exec proc_worst_supplier_test '1998','04'

我有一个错误

无效的对象名称“y”

4

1 回答 1

0

试试这个:

;WITH CTE as (
SELECT s.CompanyName,(select min(t.b) from (select (round(sum(OD.Quantity * (1-OD.Discount) * OD.UnitPrice),0)) as b from [Order Details] group by ProductID) t) as q
FROM ((((Products p 
inner join [Order Details] OD on p.ProductID=OD.ProductID) 
inner join Categories c on p.CategoryID=c.CategoryID) 
inner join Suppliers s on p.SupplierID=s.SupplierID)
inner join Orders o on o.OrderID=od.OrderID)
where c.CategoryName='Produce' AND SUBSTRING(CONVERT(nvarchar(22), o.OrderDate, 111),1,4)=@datey AND SUBSTRING(CONVERT(nvarchar(22),o.OrderDate, 111),6,2)=@datem
group by s.CompanyName
)

select CompanyName from CTE where q=(select MIN(q) from CTE)
于 2012-10-10T05:22:54.103 回答