H2选择表达式列别名

时间:2015-07-07 05:58:36

标签: sql select h2 column-alias

有H2表:

CREATE TABLE IF NOT EXISTS sometable (ondate DATE NOT NULL);

使用数据

INSERT INTO sometable VALUES ('2015-07-07');
INSERT INTO sometable VALUES ('2014-07-07');
INSERT INTO sometable VALUES ('2013-07-07');

我想限制所选的数据量,但以下选择不起作用。为什么呢?

SELECT YEAR(CONVERT(ondate, TIMESTAMP)) AS yr FROM sometable WHERE yr = 2015

错误消息是SELECT YEAR(CONVERT(ondate,TIMESTAMP))AS yr FROM sometable WHERE yr = 2015;专栏" YR"未找到; SQL语句:SELECT YEAR(CONVERT(ondate,TIMESTAMP))AS yr FROM sometable WHERE yr = 2015 [42122-176] 42S22 / 42122

3 个答案:

答案 0 :(得分:2)

这不是特定于H2的,这将在许多RDBMS上发生。 yr列实际上不是SELECT子句的一部分,它是CONVERT语句。如果要这样做,请将整个语句包装在派生表中并查询,或者使用与WHERE中的SELECT相同的子句。

例如;

SELECT * FROM (SELECT YEAR(CONVERT(ondate, TIMESTAMP)) AS yr 
FROM sometable) a WHERE a.yr = 2015

OR

SELECT YEAR(CONVERT(ondate, TIMESTAMP)) AS yr FROM sometable 
WHERE YEAR(CONVERT(ondate, TIMESTAMP)) = 2015

答案 1 :(得分:1)

您不能在where子句中引用列别名。

SELECT
YEAR(CONVERT(ondate, TIMESTAMP)) AS yr
FROM sometable
WHERE YEAR(CONVERT(ondate, TIMESTAMP)) = 2015

答案 2 :(得分:1)

错误表明未找到列yr,因为yr不是您的列名,它只是一个别名。 SQL不能将别名视为可以这样写的列名

SELECT 
    YEAR(CONVERT(ondate, TIMESTAMP)) AS yr 
FROM sometable WHERE 
    YEAR(CONVERT(ondate, TIMESTAMP)) = 2015