The approach will depend on the bank you are using, but in general the idea is to think of relationships.
When we say that a bank is relational we say that it works with relationships, and contrary to what some people think relationships are not relationships between tables.
Suppose you have an x table as below:
Coluna - Tipo
id - number
nome - varchar
sobrenome - varchar
email - varchar
In this case something like:
SELECT DISTINCT nome, email FROM x
is a relationship.
Armed with this information we can now think about how to work relationships.
Some banks have the WITH figure, which allows creating relationships to then use in queries.
Armed with this two information we can do something like this:
WITH relacao_um as (
SELECT
AVG (UR1_Demanda) as UR1_DemandaAVG,
DATEPART(dayofyear, E3TimeStamp) as id
FROM MTC_CF_MM
WHERE UR1_Demanda <> 0
GROUP BY DATEPART(dayofyear, E3TimeStamp)
ORDER BY id
), relacao_dois as (
SELECT
AVG (UR2_Demanda) as UR2_DemandaAVG,
DATEPART(dayofyear, E3TimeStamp) as id
FROM MTC_CF_MM
WHERE UR2_Demanda <> 0
GROUP BY DATEPART(dayofyear, E3TimeStamp)
ORDER BY id
)
SELECT *
FROM relacao_um
INNER JOIN relacao_2 ON relacao_um.id = relacao_2.id
Another approach that is possible in some banks (not all will accept): is to include the direct link in JOIN:
SELECT *
FROM (
SELECT
AVG (UR1_Demanda) as UR1_DemandaAVG,
DATEPART(dayofyear, E3TimeStamp) as id
FROM MTC_CF_MM
WHERE UR1_Demanda <> 0
GROUP BY DATEPART(dayofyear, E3TimeStamp)
ORDER BY id
) as A
INNER JOIN (
SELECT
AVG (UR2_Demanda) as UR2_DemandaAVG,
DATEPART(dayofyear, E3TimeStamp) as id
FROM MTC_CF_MM
WHERE UR2_Demanda <> 0
GROUP BY DATEPART(dayofyear, E3TimeStamp)
ORDER BY id
) as B ON A.id = B.id
I hope I’ve helped, keeping in mind that relational banks work with relationships makes life a lot easier.
And how does this Union make Join, which is the question of the question? in addition, it is important to add a note that this only works if both selects have the same number of fields/types
– Ricardo Pontual