Skip to content

Instantly share code, notes, and snippets.

@vwedesam
Last active April 27, 2023 17:44
Show Gist options
  • Save vwedesam/c4a9474960958274998573e78b69ce82 to your computer and use it in GitHub Desktop.
Save vwedesam/c4a9474960958274998573e78b69ce82 to your computer and use it in GitHub Desktop.
SQL Re-Use alias named columns

SQL Re-Use alias named columns

USE named alias in SQL statement

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

E.g

SQL Calculate sum of two alias named columns

WITH SUMS AS 
(
   SELECT
      col1, col2, 
      SUM(col1) + SUM(col2) as Total,
      SUM(col1) + SUM(col2) as Total1 
   FROM
      table
   GROUP BY
      col1, col2
)
SELECT 
   col1, col2, 
   total, total1, 
   (total + total1) AS 'GrandTotal' 
FROM 
   SUMS
   
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment