如何在第一个中引用值从联盟中的第二个选择中选择?

时间:2018-01-24 19:00:47

标签: sql sql-server union

我正在尝试将计算字段的“总和”行添加到我的每个“销售代表”的查询结果中。我相信我应该使用union来添加额外的行,但我不想再重新计算每个字段。

这是预期的结果:

|SalesRep|Field1|Field2|CalculatedField|
------------------------------------------
|Bob     |value  |value  |12,000         |
|Bob     |value  |value  |3,000          |
|BobTotal|       |       |Sum(Calculated)|
|Tom     |value  |value  |400            |
|Tom     |value  |value  |800            |
|TomTotal|       |       |Sum(Calculated)|

所以基本上,我现在有这个:

SELECT SalesRep, Field1, Field2, (The Calculated Field)
FROM SalesRepTbl1
union
SELECT SalesRep, Field1, Field2, (The Calculated Field)
FROM SalesRepTbl2

这是我需要的所有数据,但不是计算字段的总和。我的下一步是什么?

谢谢!

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找grouping sets

select SalesRep, Field1, Field2, sum(calculated_field) as calculated_field
from ((SELECT SalesRep, Field1, Field2, ? as calculated_field
       FROM SalesRepTbl1
      ) union all
      (SELECT SalesRep, Field1, Field2, ? as calculated_field
       FROM SalesRepTbl2
      )
     ) s
group by grouping sets ( (SalesRep, Field1, Field2), (SalesRep) );

注意我将子查询更改为使用union all而不是union,因为我认为您不希望产生删除重复项的开销。

答案 1 :(得分:0)

SELECT SalesRep, Field1, Field2, (The Calculated Field)
FROM SalesRepTbl1
union
SELECT 'BobTotal' as Salesrep,  NULL as Field1, NULL as field2, sum(CalculatedField) as CalcualtedField
FROM SalesRepTbl1
union
SELECT SalesRep, Field1, Field2, (The Calculated Field)
FROM SalesRepTbl2
union
SELECT 'TomTotal' as Salesrep,  NULL as Field1, NULL as field2, sum(CalculatedField) as CalcualtedField
FROM SalesRepTbl2