Group By Column Alias

懵懂的女人 提交于 2019-12-13 14:28:59

问题


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

回答1:


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.




回答2:


Your questions says "variable", but I think you mean column alias. Just FYI.

Using the actual column definition should work fine. Untested, but this should do what you need:

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
    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 


来源:https://stackoverflow.com/questions/11145123/group-by-column-alias

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!