protected override Expression VisitSelect(SelectExpression select)
        {
            var saveIsOuterMostSelect = _isOutermostSelect;
            try
            {
                _isOutermostSelect = false;
                select = (SelectExpression)base.VisitSelect(select);

                var hasOrderBy = select.OrderBy != null && select.OrderBy.Count > 0;
                var hasGroupBy = select.GroupBy != null;
                var canHaveOrderings = saveIsOuterMostSelect || select.Take != null || select.Skip != null;
                var canReceivedOrderings = canHaveOrderings && !hasGroupBy && !select.IsDistinct;

                if (hasOrderBy)
                    PrependOrderings(select.OrderBy);

                IEnumerable<OrderExpression> orderings = null;
                if (canReceivedOrderings)
                    orderings = _gatheredOrderings;
                else if (canHaveOrderings)
                    orderings = select.OrderBy;

                var canPassOnOrderings = !saveIsOuterMostSelect && !hasGroupBy && !select.IsDistinct;
                ReadOnlyCollection<FieldDeclaration> fields = select.Fields;
                if (_gatheredOrderings != null)
                {
                    if (canPassOnOrderings)
                    {
                        var producedAliases = new DeclaredAliasGatherer().Gather(select.From);

                        BindResult project = RebindOrderings(_gatheredOrderings, select.Alias, producedAliases, select.Fields);
                        _gatheredOrderings = null;
                        PrependOrderings(project.Orderings);
                        fields = project.Fields;
                    }
                    else
                        _gatheredOrderings = null;
                }
                if (orderings != select.OrderBy || fields != select.Fields)
                    select = new SelectExpression(select.Alias, fields, select.From, select.Where, orderings, select.GroupBy, select.IsDistinct, select.Skip, select.Take);

                return select;
            }
            finally
            {
                _isOutermostSelect = saveIsOuterMostSelect;
            }
        }
 private void MapAliases(Expression a, Expression b)
 {
     var gatherer = new DeclaredAliasGatherer();
     Alias[] prodA = gatherer.Gather(a).ToArray();
     Alias[] prodB = gatherer.Gather(b).ToArray();
     for (int i = 0, n = prodA.Length; i < n; i++)
     {
         _aliasScope.Add(prodA[i], prodB[i]);
     }
 }