使用子查询将查询结果声明为查询结果

时间:2016-10-27 15:28:14

标签: mysql sql-server

我在这个领域很新,我想知道是否可能以及如何修复我写的代码:

begin;

DECLARE @income BIGINT;
DECLARE @outcome BIGINT;

set @income = (select cars_carID as y, (sum(datediff(returndate,rentdate)) * dayprice from rentals,cars where cars_carID= y) group by carID);

set @outcome=(select carID as x, (sum(maint_price) from maintenance,cars where Maint_carID = x) group by maint_carID);

select @income-@outcome;

end;

查询没问题,但它一直给我很少的变量错误,并编写了一些查询组合,如:

Select 
Cars_carID as x, 
(
    select 
    (
        select (sum(datediff(returndate,rentdate)) * dayprice)-(sum(Maint_Price)  
        from rentals, cars, maintenance 
        where cars_carID=carID 
            and Maint_carID = x 
        group by carID
    )
)

这是无休止的。

1 个答案:

答案 0 :(得分:0)

首先你有这个问题:
您的查询获得2个值,并希望将它们存储在一个变量中 这不起作用。

DECLARE @income BIGINT; 
DECLARE @outcome BIGINT;

set @income = (select cars_carID as y, 
                      (sum(datediff(returndate,rentdate)) * dayprice) 
               from rentals,
                    cars 
               where cars_carID= y
               group by carID
              );

将其更改为:

set @income = (select (sum(datediff(returndate,rentdate)) * dayprice) 
               from rentals
                 inner join cars on rentals.carID = cars.CarID
               group by carID
              );

此查询仍然无法运行,因为carID在group by中而不在select子句中,但是如果不知道你需要什么,我就无法完成查询。
它应该能够让你继续前进

也许应该是这样的

set @income = select sum(t.result)
              from   (select cars.carID,    
                             (sum(datediff(returndate,rentdate)) * dayprice) as result 
                      from rentals
                        inner join cars on rentals.carID = cars.CarID
                      group by carID
                    ) t
相关问题