I'm a bit new to SQL, so please be gentle...
I'm attempting to create a [legacy] BigQuery SQL self union like:
SELECT * FROM (query 1), (query 1)
Syntax found from another SO answer here. However query 1 is very long, and I don't want to have to copy/paste the entire query multiple times. Is there a way to name query 1 so I don't have to paste the whole thing over again?
I'm trying to do something like the following (with regards to the references to A
):
SELECT
*
FROM
(query 1) AS A,
(SELECT
Category as Hier_Level,
MAX(Department),
Category,
"VARIOUS" AS Subcategory,
SUM(DOLLARS)
FROM
A
GROUPBY
Category) AS B,
(SELECT
Department as Hier_Level,
Department,
"VARIOUS" AS Category,
"VARIOUS" AS Subcategory,
SUM(DOLLARS)
FROM
A
GROUPBY
Department,
Category) AS C,
...
Update
While the question is focused on not repeating query 1's code, the final goal of the aggregation is to take data like the following, which is output by query 1:
Hier_Level Department Category Subcategory Dollars
Subcategory Electronics TV LCD 3500
Subcategory Electronics TV OLED 6000
Subcategory Electronics Phone iPhone 600
and return the same table with rows added for aggregations from groupbys. Results should look like:
Hier_Level Department Category Subcategory Dollars
Subcategory Electronics TV LCD 3500
Subcategory Electronics TV OLED 6000
Subcategory Electronics Phone iPhone 600
Category Electronics TV Various 9500
Category Electronics Phone iPhone 600
Department Electronics Various Various 10100
In standard SQL it's my understanding that something like this can be accomplished using CTE and union all, but neither are available in BQ Legacy SQL.