从两个查询中计算值

时间:2010-12-09 12:53:07

标签: sql-server

SQL服务器中有哪种方法可以计算两个单独查询的结果?例如:

Select sum(product) as Items1
From product1

Items1
8,958

Select sum(product) as Items2
From product2

Items2
40,465

现在,我想得到Items1的百分比除以Items2(8,958 / 40,465),这给了我22%。我想问一下是否可以在SQL server中使用查询来完成。非常感谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)