如何汇总选择语句中的列

时间:2019-08-06 10:46:39

标签: sql sql-server

我要选择其他列,并希望创建另一列以特定方式计算的列。一次性创建列并在选择部分中声明它们时,如何解决此问题。

我试图将它们放在FROM语句中,但是我认为我做错了,对我而言,如何做到这一点并不十分明显。我还尝试将每个总和“替换”为整个查询,但均无济于事。

SELECT 

SUM(CASE WHEN 
Table.Code = 'Golden' 
THEN
Booking.Amount 
ELSE 
0.0 
END) AS Money1,

SUM(CASE WHEN 
Table.Code = 'Monkey' 
THEN
Booking.Amount 
ELSE 
0.0 
END) AS Money2,

(Money1 + Money2) AS "Golden Monkey"

FROM Table
Where ...

它总是带有文本“无效的列名”的下划线。我该如何解决?

3 个答案:

答案 0 :(得分:1)

您可以尝试以下操作-因为您不能使用列别名来计算另一列

SELECT 

SUM(CASE WHEN Table.Code = 'Golden' THEN Booking.Amount ELSE 0.0 END) AS Money1,
SUM(CASE WHEN Table.Code = 'Monkey' THEN Booking.Amount ELSE 0.0 END) AS Money2,
SUM(CASE WHEN Table.Code in ('Golden','Monkey') THEN Booking.Amount ELSE 0.0 END) as "Golden Monkey"
FROM Table Where ...

答案 1 :(得分:1)

您可以使用子查询来获得所需的结果。

Select money1, money2, money1 + moeny2 from (
    SELECT 

    SUM(CASE WHEN 
    Table.Code = 'Golden' 
    THEN
    Booking.Amount 
    ELSE 
    0.0 
    END) AS Money1,

    SUM(CASE WHEN 
    Table.Code = 'Monkey' 
    THEN
    Booking.Amount 
    ELSE 
    0.0 
    END) AS Money2

    FROM Table
    Where ...
) as d

答案 2 :(得分:0)

使用cte,您不能在同一级别使用列名的别名

with cte as
(
SELECT 

SUM(CASE WHEN 
Table.Code = 'Golden' 
THEN
Booking.Amount 
ELSE 
0.0 
END) AS Money1,

SUM(CASE WHEN 
Table.Code = 'Monkey' 
THEN
Booking.Amount 
ELSE 
0.0 
END) AS Money2 


FROM Table
Where ...
) select (Money1 + Money2) AS "Golden Monkey" from cte