3

我有以下疑问。我想使用别名并将它们添加在一起,但 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*/
4

4 回答 4

4

您可以将查询包装为子查询

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
于 2012-07-13T13:32:37.800 回答
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*/
于 2012-07-13T13:42:39.833 回答
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
于 2012-07-13T13:31:52.060 回答
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
于 2012-07-13T13:32:32.230 回答