计算 sum() 两个别名命名的列 - 在 sql 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3932205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 07:55:56  来源:igfitidea点击:

To calculate sum() two alias named columns - in sql

sqlsumalias

提问by Innova

To calculate sum() of two temp column names declared in query - in SQL

计算在查询中声明的两个临时列名称的 sum() - 在 SQL 中

studtable has only two columns m1,m2. total and total1 is given as temp name.

stud表只有两列m1,m2。total 和 total1 作为临时名称给出。

select 
   m1, m2, 
   SUM(m1) + SUM(m2) as Total,
   SUM(m1) + SUM(m2) as Total1 
from 
   stud 
group by 
   m1, m2

How to calculate grandtotalas sum(total)+sum(total1)with the column name declared as temp name for the query to execute.

如何使用声明为临时名称的列名称进行计算grandtotalsum(total)+sum(total1)以便执行查询。

With cte dosn't support duplicate column names?

cte 不支持重复的列名?

How to make use of it to support duplicate columnname

如何利用它来支持重复的列名

回答by marc_s

You can't do it directly - you need to use something like a CTE (Common Table Expression) - like this:

您不能直接执行此操作 - 您需要使用类似 CTE(公用表表达式)之类的东西 - 如下所示:

;WITH sums AS 
(
   SELECT
      m1, m2, 
      SUM(m1) + SUM(m2) as Total,
      SUM(m1) + SUM(m2) as Total1 
   FROM
      dbo.stud 
   GROUP BY
      m1, m2
)
SELECT 
   m1, m2, 
   total, total1, 
   total+total1 AS 'GrandTotal' 
FROM 
   sums

This works in SQL Server 2005 and newer (and also in some other database systems that support CTE's - which is an ANSI standard).

这适用于 SQL Server 2005 和更新版本(以及支持 CTE 的其他一些数据库系统 - 这是一种 ANSI 标准)。

回答by shweta

select convert(int, first)+ convert(int,second) as total from test1 

in this first and second is field datatype is nvarchar, and if fields are in integerthen

在这第一个和第二个是字段数据类型是nvarchar,如果字段在integer然后

select first+second as total from test1 , test1

is table name.

是表名。