我在下面有以下问题。我想使用别名并将它们一起添加,但SQL不允许这样做。有关如何在不重复查询的情况下进行此操作的任何建议?使用Microsoft SQL Server 2008
SELECT
SUM(CASE WHEN rg.category = 'Space' THEN ((rg.score*20)) END) As space,
SUM(CASE WHEN rg.category = 'QPR' THEN ((rg.score*20)) END) As qpr,
(space + qpr) As result
FROM rg_fin As rg JOIN...../*query goes on*/
答案 0 :(得分:1)
您可以使用子查询执行此操作:
select
space,
qpr,
(space + qpr) As result
from (
select
SUM(CASE WHEN rg.category = 'Space' THEN ((rg.score*20)) END) As space,
SUM(CASE WHEN rg.category = 'QPR' THEN ((rg.score*20)) END) As qpr,
FROM rg_fin As rg JOIN...../*query goes on*/
) as a
答案 1 :(得分:1)
您可以将查询包装为子查询
SELECT *,
(space + qpr) As result
FROM
(
SELECT
SUM(CASE WHEN rg.category = 'Space' THEN ((rg.score*20)) END) As space,
SUM(CASE WHEN rg.category = 'QPR' THEN ((rg.score*20)) END) As qpr
....
) subquery
答案 2 :(得分:1)
如果要使用别名,则需要将查询包装在另一个查询中:
SELECT space
, qpr
, space + qpr as result
FROM
(
SELECT
SUM(CASE WHEN rg.category = 'Space' THEN ((rg.score*20)) END) As space,
SUM(CASE WHEN rg.category = 'QPR' THEN ((rg.score*20)) END) As qpr,
(space + qpr) As result
FROM rg_fin As rg JOIN...../*query goes on*/
) x
或者,如果您不需要使用别名,则可以重复以下字段:
SELECT
SUM(CASE WHEN rg.category = 'Space' THEN ((rg.score*20)) END) As space,
SUM(CASE WHEN rg.category = 'QPR' THEN ((rg.score*20)) END) As qpr,
(SUM(CASE WHEN rg.category = 'Space' THEN ((rg.score*20)) END)
+ SUM(CASE WHEN rg.category = 'QPR' THEN ((rg.score*20)) END)) As result
FROM rg_fin As rg JOIN...../*query goes on*/
答案 3 :(得分:0)
使用派生表
SELECT
space,qpr,(space + qpr) As result
FROM
(
SELECT
SUM(CASE WHEN rg.category = 'Space' THEN ((rg.score*20)) END) As space,
SUM(CASE WHEN rg.category = 'QPR' THEN ((rg.score*20)) END) As qpr,
(space + qpr) As result
FROM rg_fin As rg JOIN...../*query goes on*/
) as t