简体   繁体   English

根据子查询的查询结果声明变量

[英]Declare variables as result of query with subquery

I am pretty new in this field and I'd like to know if it's possible and how to fix this code that I wrote: 我在这个领域还很新,我想知道是否有可能以及如何修复我编写的代码:

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;

The queries are ok but it keep giving me few errors on variables and writing a combination of queries like: 查询是可以的,但是它使我在变量上几乎没有错误,并且编写了以下查询组合:

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
    )
)

it's neverending. 它永无止境。

For start you have this problem : 首先,您有这个问题:
Your query gets 2 values and want to store them in one variable. 您的查询获取2个值,并希望将它们存储在一个变量中。
That does not work. 那行不通。

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
              );

Change it to something like this : 将其更改为如下所示:

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

This query will still not run because carID is in the group by and not in the select clause, but without knowning exactly what you need I cant complete the query. 该查询仍然不会运行,因为carID在group by中,而不在select子句中,但是在不知道您需要什么的情况下,我无法完成查询。
It should be able to get you on your way though 它应该能够带你上路

Maybe it should be like this 也许应该是这样

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM