2016-10-27 8 views
0

でクエリの結果として変数を宣言し、どのように私が書いたこのコードを修正する:私はこの分野ではかなり新しいですし、私はそれが可能だかどうかを知りたいのですが、サブクエリ

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 @[email protected]; 

end; 

をクエリはOKですがが、変数に関するエラーを少なくして、次のようなクエリの組み合わせを作成し続けます。

それはまったくありません。

+0

ようにする必要があり

かかわらず、あなたの方法であなたを得ることができる必要があり、これはMySQLのか、SQL Serverのでしょうか? – GuidoG

+1

皆様のご健勝のために、SQL-99結合(内部結合、左外結合など)をお読みください。あなたが現在やっているやり方は恐ろしいことに時代遅れで、問題を起こしやすい – DForck42

答えて

0

最初にこの問題があります。
クエリは2つの値を取得し、1つの変数に格納します。
それは動作しません。

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はしていないselect句では、しかし、あなたは、私はカント必要まさにknowningなしでグループ内にあるため、このクエリはまだ実行されませんクエリを完了します。
それはたぶん、それがこの

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 
関連する問題