2010-12-09 74 views
0

SQL Server中是否有方法可以計算兩個單獨查詢的結果?例如:現在計算兩個查詢中的值

Select sum(product) as Items1 
From product1 

Items1 
8,958 

Select sum(product) as Items2 
From product2 

Items2 
40,465 

,我想獲得通過Items2分,給了我22%Items1的百分比(8958/40,465)。我想問問這是否可以在SQL服務器中使用查詢來完成。非常感謝!

回答

2

的一種方法是使用變量

DECLARE @Sum1 FLOAT, 
     @Sum2 FLOAT 

Select @Sum1 = sum(product) as Items1 
From product1 

Select @Sum2 = sum(product) as Items2 
From product2 

SELECT @Sum1/@Sum2 

另一個辦法是像

SELECT Items1/Items2 
FROM (
      Select sum(product) as Items1 From product1 
     ) a, 
     (
      Select sum(product) as Items2 From product2 
     ) b 
+0

謝謝大家!查詢選擇Items1/Items2 FROM( SELECT SUM(產物),爲Items1從產品1 )一個, ( SELECT SUM(產物),爲Items2從產品2 )b 運行,但返回一個0值。任何理由爲什麼? – joe 2010-12-09 13:29:04

0
select items1/items2 
    from (select sum(product) as items1 from product1) 
     ,(select sum(product) as items2 from product2) 

select (select sum(product) as items1 from product1)/
     (select sum(product) as items2 from product2)