Repository: tobymao/sqlglot

Issue:
Unaliased sub-query in a with statement (CTE?) confused the optimizer
### Short Description
When using a `select` along with a `with` statement, that has an embedded subquery, the optimizer gets confused.

### Code Snippet
The short version (full code provided below):
```python
table1_view = Select().select('id', 'sub_type').from_('table1')
select_from_sub_query = subquery(table1_view).select('id AS mainId', 'sub_type')
e = Select().select('*').from_('cte1').with_('cte1', as_=cte)
execute(e, tables=tables, schema=schema)
```

### The Error
The above fails with the following error:
```
Ambiguous columns: [(COLUMN this: 
  (IDENTIFIER this: id, quoted: False)), (COLUMN this: 
  (IDENTIFIER this: sub_type, quoted: False))]
```

But the SQL is unambiguous:
```sql
WITH cte1 AS (
    SELECT id AS mainId, sub_type FROM (SELECT id, sub_type FROM table1)
) 
SELECT * FROM cte1
```

### Workaround
Simply adding an alias to the inner subquery: `subquery(table1_view, alias='a')` solves the issue.

### Notes
This example looks contrived (`WITH` statement with an inner subquery) but it was greatly simplified from a real-world scenario. The produced SQL (without the alias) was successfully executed in a real environment (BigQuery specifically).

### Fully Working Example
Use `pytest` to run.

```python
import pytest
from sqlglot.errors import OptimizeError
from sqlglot.executor import execute
from sqlglot.expressions import Select, subquery

schema = {
    'table1': {
        'type': 'str',
        'id': 'str',
        'parent_id': 'str',
        'sub_type': 'str'
    }
}

tables = {t: [] for t in schema}

table1_view = Select()\
        .select('id', 'sub_type')\
        .from_('table1')


def test_unaliased_sub_query_in_with():
    select_from_sub_query = subquery(table1_view)\
        .select('id AS mainId', 'sub_type')
    e = _get_expression(select_from_sub_query)

    with pytest.raises(OptimizeError, match='Ambiguous') as ex_info:
        execute(e, tables=tables, schema=schema)

    print(f'\n{ex_info.value}\n')


def test_aliased_sub_query_in_with():
    select_from_sub_query = subquery(table1_view, alias='some_alias')\
        .select('id AS mainId', 'sub_type')
    e = _get_expression(select_from_sub_query)
    execute(e, tables=tables, schema=schema)


def _get_expression(cte):
    e = Select() \
        .select('*') \
        .from_('cte1') \
        .with_('cte1', as_=cte)
    print(f'\n{e.sql(pretty=False)}\n')
    return e
```


Discussion:

Resolving patch:
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -1784,7 +1784,7 @@ def subquery(self, alias=None, copy=True) -> Subquery:
         instance = _maybe_copy(self, copy)
         return Subquery(
             this=instance,
-            alias=TableAlias(this=to_identifier(alias)),
+            alias=TableAlias(this=to_identifier(alias)) if alias else None,
         )
 
     def limit(self, expression, dialect=None, copy=True, **opts) -> Select:


Test patch:
diff --git a/tests/test_executor.py b/tests/test_executor.py
--- a/tests/test_executor.py
+++ b/tests/test_executor.py
@@ -401,6 +401,16 @@ def test_execute_subqueries(self):
             ],
         )
 
+        table1_view = exp.Select().select("id", "sub_type").from_("table1").subquery()
+        select_from_sub_query = exp.Select().select("id AS id_alias", "sub_type").from_(table1_view)
+        expression = exp.Select().select("*").from_("cte1").with_("cte1", as_=select_from_sub_query)
+
+        schema = {"table1": {"id": "str", "sub_type": "str"}}
+        executed = execute(expression, tables={t: [] for t in schema}, schema=schema)
+
+        self.assertEqual(executed.rows, [])
+        self.assertEqual(executed.columns, ("id_alias", "sub_type"))
+
     def test_correlated_count(self):
         tables = {
             "parts": [{"pnum": 0, "qoh": 1}],