SQL中两个计算列的总和

时间:2016-11-15 05:31:27

标签: sql sql-server

我正在计算这样的两行:

CASE 
    WHEN isnumeric(SUBSTRING(dbo.Table.RNumber,1,CHARINDEX('+',dbo.Table.RNumber) - 1)) = 1
        THEN SUBSTRING(dbo.Table.RNumber,1,CHARINDEX('+',dbo.Table.RNumber) - 1) 
    else 0 
end AS RoomNumber,
CASE 
    WHEN isnumeric(SUBSTRING(dbo.Table.R.Number,CHARINDEX('+',dbo.Table.RNumber) + 1,LEN(dbo.Table.R.Number))) = 1
        THEN SUBSTRING(dbo.Table.R.Number,CHARINDEX('+',dbo.Table.RNumber) + 1,LEN(dbo.Table.R.Number)) 
    else 0 
end AS HallNumber,

我需要创建另一个计算RoomNumber和HallNumber之和的列,我试过这个:

SELECT *, (RoomNumber + HallNumber) AS Sum
FROM Table

但是我的列名错误无效。 我怎样才能得到这两列的总和?感谢。

2 个答案:

答案 0 :(得分:5)

您实际上只有两个选项,因为您无法在定义它的同一级别重用别名。您可以将两个CASE语句加在一起:

CASE WHEN isnumeric(SUBSTRING(dbo.Table.RNumber,1,CHARINDEX('+',dbo.Table.RNumber) - 1)) = 1
     THEN SUBSTRING(dbo.Table.RNumber,1,CHARINDEX('+',dbo.Table.RNumber) - 1) 
     ELSE 0 END AS RoomNumber,
CASE WHEN isnumeric(SUBSTRING(dbo.Table.R.Number,CHARINDEX('+',dbo.Table.RNumber) + 1,LEN(dbo.Table.R.Number))) = 1
     THEN SUBSTRING(dbo.Table.R.Number,CHARINDEX('+',dbo.Table.RNumber) + 1,LEN(dbo.Table.R.Number)) 
     ELSE 0 END AS HallNumber,
(CASE WHEN isnumeric(SUBSTRING(dbo.Table.RNumber,1,CHARINDEX('+',dbo.Table.RNumber) - 1)) = 1
     THEN SUBSTRING(dbo.Table.RNumber,1,CHARINDEX('+',dbo.Table.RNumber) - 1) 
     ELSE 0 END
+
CASE WHEN isnumeric(SUBSTRING(dbo.Table.R.Number,CHARINDEX('+',dbo.Table.RNumber) + 1,LEN(dbo.Table.R.Number))) = 1
     THEN SUBSTRING(dbo.Table.R.Number,CHARINDEX('+',dbo.Table.RNumber) + 1,LEN(dbo.Table.R.Number)) 
     ELSE 0 END) AS Sum

或者您可以尝试将当前查询包装为子查询,其中您已定义的别名可用:

SELECT t.RoomNumber,
       t.HallNumber,
       (t.RoomNumber + t.HallNumber) AS Sum
FROM
(
    ... your original query ...
) t

答案 1 :(得分:2)

您需要子查询来汇总计算列。

SELECT a.*, (a.RoomNumber + a.HallNumber) AS Sum
   (SELCT  CASE 
        WHEN isnumeric(SUBSTRING(dbo.Table.RNumber,1,CHARINDEX('+',dbo.Table.RNumber) - 1)) = 1
            THEN SUBSTRING(dbo.Table.RNumber,1,CHARINDEX('+',dbo.Table.RNumber) - 1) 
        else 0 
    end AS RoomNumber,
    CASE 
        WHEN isnumeric(SUBSTRING(dbo.Table.R.Number,CHARINDEX('+',dbo.Table.RNumber) + 1,LEN(dbo.Table.R.Number))) = 1
            THEN SUBSTRING(dbo.Table.R.Number,CHARINDEX('+',dbo.Table.RNumber) + 1,LEN(dbo.Table.R.Number)) 
        else 0 
    end AS HallNumber) AS a