我似乎在掌握使用AS创建别名的概念时会遇到一些麻烦,然后再使用该别名。下面是一个非常简单的查询示例,当我运行时出现错误:
SELECT IP,
(SELECT server_ip as IP
FROM table1
WHERE start_time BETWEEN @startdate AND @enddate
Group By server_ip)X
Group By IP
我希望这只是从server_ip列中的第二个select语句返回结果。但是我收到一条错误消息,指出IP不是无效的列名。有人可以向我解释如何正确地做到这一点吗?
答案 0 :(得分:1)
SELECT IP,
(
SELECT server_ip as IP
FROM table1
WHERE start_time BETWEEN @startdate AND @enddate
Group By server_ip
)X
/*FROM WHERE ? <--------------- */
Group By IP
目前您的SELECT
声明
SELECT IP, X
GROUP BY IP
您需要一个FROM子句。 X
目前是一个非相关的子查询。我怀疑你想把它当作一个派生表,但即使这样,查询也没有意义。无需执行两次相同的GROUP BY
操作。
依赖于您的RDBMS,您也可以使用公用表表达式。这是一个有点人为的使用例子。
;WITH X AS
(
SELECT server_ip as IP
FROM table1
WHERE start_time BETWEEN @startdate AND @enddate
),
Y AS
(
SELECT IP
FROM X
Group By IP
)
SELECT IP
FROM Y
答案 1 :(得分:1)
你错过了FROM子句:
SELECT x.ip
FROM (SELECT server_ip as IP
FROM table1
WHERE start_time BETWEEN @startdate AND @enddate
GROUP BY server_ip) AS x
GROUP BY x.ip
原样,你只需要使用:
SELECT server_ip as IP
FROM table1
WHERE start_time BETWEEN @startdate AND @enddate
GROUP BY server_ip
答案 2 :(得分:0)
您必须在新名称前使用AS
关键字为临时表或列等分配别名。