Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

alias

sql

sum

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

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

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

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

With cte dosn't support duplicate column names?

How to make use of it to support duplicate columnname

like image 901
Innova Avatar asked Oct 14 '10 10:10

Innova


People also ask

Can we use alias in calculation in SQL?

Using the CALCULATED Keyword with Column AliasesThe CALCULATED keyword enables PROC SQL users to reference column aliases that are associated with calculated expressions. The column alias referenced by the CALCULATED keyword can be in the WHERE clause, ON clause, GROUP BY clause, HAVING clause, or ORDER BY clause.

How do you calculate two columns in SQL?

All you need to do is use the multiplication operator (*) between the two multiplicand columns ( price * quantity ) in a simple SELECT query. You can give this result an alias with the AS keyword; in our example, we gave the multiplication column an alias of total_price .


1 Answers

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

;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).

like image 76
marc_s Avatar answered Sep 22 '22 08:09

marc_s