按列别名分组 [英] Group By Column Alias

查看:126
本文介绍了按列别名分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按列别名分组sql语句。在本质上,我希望下面的功能应该是逻辑上的,但是使用as创建的列是不允许的。 (无效的列名称)。任何人有任何提示?

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


推荐答案

对于分组的直接问题,您需要

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

另一方面,您不应该使用 VARCHAR(MAX),如果没有必要。

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

这篇关于按列别名分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆