To calculate sum() two alias named columns - in sql
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).
How to use the sum of two aliases in an order by clause in postgres?
Do it like this:
select * from (
SELECT *,
(SELECT COUNT(*) FROM upvote up WHERE up.post_id = post.id) AS upvotes,
(SELECT COUNT(*) FROM downvote dw WHERE dw.post_id = post.id) AS downvotes
FROM post) A
ORDER BY (upvotes+downvotes) DESC;
Here is a small DEMO for Postgresql 12.
How to calculate sum from Alias column in MySQL?
Yes, you can't use the alias at the same level. You need to write an upper layer of query to use the alias
Considering the logic of the code is already working, just correcting the syntax to use alias
Here is how it is
SELECT
sum(CASE when quality_class =1 then trees_ha else 0 end)/get_total_forest_plots() + sum(CASE when quality_class =3 then trees_ha else 0 end)/get_total_forest_plots())/sum(initial_data.total) *1
FROM
(SELECT
sum(CASE when quality_class =1 then trees_ha else 0 end)/get_total_forest_plots() + sum(CASE when quality_class =2 then trees_ha else 0 end)/get_total_forest_plots() as total
From
<Table name>
) initial_data
Is there a way to calculate a SUM of a Count Alias in SQL?
You could use analytic functions here:
SELECT
WrapupData,
ISNULL(WrapupData, 'No Dispos Code Entered') AS DispositionCode,
COUNT(WrapupData) AS DispositionCount,
SUM(COUNT(WrapupData)) OVER () AS Total,
100.0 * COUNT(WrapupData) / SUM(COUNT(WrapupDatalse)) OVER () AS Percentage
FROM Termination_Call_Detail tcd
LEFT JOIN dbo.t_Call_Type ct
ON ct.CallTypeID = tcd.CallTypeID
GROUP BY
WrapupData;
The here is to use SUM()
with a window over the entire table, post aggregation, to find the total. We can also find the percentage by normalizing the count using this sum.
Related Topics
SQL Query to Join Two Tables Based Off Closest Timestamp
Oracle SQL Returns Rows in Arbitrary Fashion When No "Order By" Clause Is Used
SQL Inner Join on Select Statements
Postgresql Update Multiple Tables in Single Query
SQL Syntax to Pivot Multiple Tables
Detect Duplicate Items in Recursive Cte
Using Variables in Classic Asp Parameterized SQL
How to Use in Clause with Preparedstatement in Postgresql
How to Execute a Stored Procedure Over a Set Without Using a Cursor
How to Create Xml Schema from an Existing Database in SQL Server 2008
Group by Every N Records in T-Sql
Using Pivot to Flip Data from Wide to Tall
Rename Single Column in Select * in SQL, Select All But a Column