在GROUP BY子句中使用别名

时间:2014-11-19 10:53:50

标签: sql-server group-by alias

以下代码正常运行:

SELECT
    ISNULL(U.username, U.users_id) AS users_name,
    CONVERT(varchar(20), H.date_time, 103) AS date_time,
    SUM(sale_val) AS sales_val
FROM
    res R
        INNER JOIN invoice_hdr H ON H.guid = R.guid
        INNER JOIN users U ON U.user_no = H.user_no
GROUP BY
    ISNULL(U.username, U.users_id),
    CONVERT(varchar(20), H.date_time, 103)

但是我发现GROUP BY子句是多余的,并尝试了GROUPing BY别名:

GROUP BY
    users_name,
    date_time

我收到以下错误:

  

无效的列名'users_name'

date_time相同。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:1)

是的,将其包装在子查询中并在外层执行聚合:

select sq.users_name, sq.date_time, sum(sq.sale_var)
from (
SELECT
    ISNULL(U.username, U.users_id) AS users_name,
    CONVERT(varchar(20), H.date_time, 103) AS date_time,
    sale_val
FROM
    res R
        INNER JOIN invoice_hdr H ON H.guid = R.guid
        INNER JOIN users U ON U.user_no = H.user_no
) sq
GROUP BY sq.users_name, sq.date_time;

ORDER BY是唯一可以在同一级别上使用其定义引用别名的地方。

答案 1 :(得分:0)

SELECT RR.users_name,RR.date_time,SUM(RR.sale_val) Sale FROM 
(
SELECT
    ISNULL(U.username, U.users_id) AS users_name,
    CONVERT(varchar(20), H.date_time, 103) AS date_time,
    sale_val 
FROM
    res R
        INNER JOIN invoice_hdr H ON H.guid = R.guid
        INNER JOIN users U ON U.user_no = H.user_no

        ) RR
GROUP BY
    RR.users_name,
    CONVERT(varchar(20), RR.date_time, 103)