**How to reproduce**
Clickhouse version 21.2-21.3

```
SELECT x
FROM
(
    SELECT 1 AS x
    UNION DISTINCT
    SELECT 1
)
LIMIT 1

Query id: b82bbb8d-dea9-4f1c-9a2f-5b0e9b6c2422


0 rows in set. Elapsed: 0.002 sec.

Received exception from server (version 21.2.3):
Code: 49. DB::Exception: Received from localhost:9000. DB::Exception: Bad cast from type DB::ASTSelectWithUnionQuery to DB::ASTSelectQuery.
```


{
    
    
    std::vector<const WindowDescription *> windows_sorted;
    for (const auto & [_, w] : query_analyzer->windowDescriptions())
    {
        windows_sorted.push_back(&w);
    }
    std::sort(windows_sorted.begin(), windows_sorted.end(),
        windowDescriptionComparator);
    const Settings & settings = context->getSettingsRef();
    for (size_t i = 0; i < windows_sorted.size(); ++i)
    {
        const auto & w = *windows_sorted[i];
        if (i == 0 || !sortIsPrefix(w, *windows_sorted[i - 1]))
        {
            auto partial_sorting = std::make_unique<PartialSortingStep>(
                query_plan.getCurrentDataStream(),
                w.full_sort_description,
                0 ,
                SizeLimits(settings.max_rows_to_sort, settings.max_bytes_to_sort,
                    settings.sort_overflow_mode));
            partial_sorting->setStepDescription("Sort each block for window '"
                + w.window_name + "'");
            query_plan.addStep(std::move(partial_sorting));
            auto merge_sorting_step = std::make_unique<MergeSortingStep>(
                query_plan.getCurrentDataStream(),
                w.full_sort_description,