Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group By Column Alias

I want to group an sql statement by a column alias. In essense, I want the below to function as it should logically, but grouping by a column created with an as is not allowed. (Invalid column name). Anyone got any tips?

SELECT 
    CASE
    WHEN Date IS NULL
    THEN 'EMPTY'
    ELSE
        CASE
        WHEN Date = '1/1/1753'
        THEN 'UNAVAILABLE'
        ELSE CAST(MONTH(Date) as varchar(MAX))+
             '/'+ CAST(YEAR(Date) as varchar(MAX))
        END
    END AS MonthYear
FROM tbltablename
GROUP BY MonthYear
like image 408
steventnorris Avatar asked Nov 26 '25 06:11

steventnorris


1 Answers

For the immediate problem of the grouping, you need to either group by the same expression or calculation of your new column, or use it from a derived table.

SELECT MonthYear
FROM (  SELECT Columns,
            CASE
            WHEN Date IS NULL
            THEN 'EMPTY'
            ELSE
                CASE
                WHEN Date = '1/1/1753'
                THEN 'UNAVAILABLE'
                ELSE CAST(MONTH(Date) as varchar(2))+
                     '/'+ CAST(YEAR(Date) as varchar(4))
                END
            END AS MonthYear
        FROM tbltablename) T
GROUP BY MonthYear

On the other hand, you shouldn't use VARCHAR(MAX) if its not necessary.

like image 53
Lamak Avatar answered Nov 28 '25 22:11

Lamak