Select from union of nested subqueries

2.9k views Asked by At

I am quite certain this is an issue with applying proper aliases, I'm just not sure where I'm going wrong. I am looking at the following UNION in sqlserver:

Select Z.DesiredResult1, etc...
from (
    Select C.columns
        from (
        Select B.columns
            from (
                Select A.columns
                from (Subquery) as A
            ) as B
        ) as C
    Where C.condition = 1
    UNION
    Select F.columns
        from (
        Select E.columns
            from (
                Select D.columns
                from (Subquery) as D
            ) as E
        ) as F
    Where F.condition = 2
) as Z

The union by itself functions perfectly, but when trying to make SELECT statements from it (as shown above) it throws an error:

No column name was specified for column 1 of 'Z'

Any insights would be appreciated, thanks for helping an SQL newbie.

Edit: Solved--I misunderstood the error. The issue was an aggregate function that needed an alias, not an entire subquery. Leaving the aggregate column unnamed worked fine for the union alone, so I didn't even consider it. Thanks for bothering to read.

1

There are 1 answers

0
McNets On

This error can be easily reproduced. Check it here.

If you do not name the columns in a single UNION

SELECT *
FROM (SELECT 'A','B') T1
UNION
SELECT *
FROM (SELECT 'C','D') T2

You will get the same error:

No column name was specified for column 1 of 'T1'.

No column name was specified for column 2 of 'T1'.

No column name was specified for column 1 of 'T2'.

No column name was specified for column 2 of 'T2'.

Simply name each common column with the same name.

SELECT T3.Result1, T3.Result2
FROM
    (SELECT *
    FROM (SELECT 'A' Result1, 'B' Result2) T1
    UNION
    SELECT *
    FROM (SELECT 'C' Result1, 'D' Result2) T2) T3

+----+---------+---------+
|    | Result1 | Result2 |
+----+---------+---------+
| 1  |    A    |    B    |
+----+---------+---------+
| 2  |    C    |    D    |
+----+---------+---------+