0

有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

4

3 回答 3

2

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

例如;

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

或者

SELECT YEAR(CONVERT(ondate, TIMESTAMP)) AS yr FROM sometable 
WHERE YEAR(CONVERT(ondate, TIMESTAMP)) = 2015
于 2015-07-07T06:08:21.687 回答
1

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

SELECT
YEAR(CONVERT(ondate, TIMESTAMP)) AS yr
FROM sometable
WHERE YEAR(CONVERT(ondate, TIMESTAMP)) = 2015
于 2015-07-07T06:07:11.967 回答
1

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

SELECT 
    YEAR(CONVERT(ondate, TIMESTAMP)) AS yr 
FROM sometable WHERE 
    YEAR(CONVERT(ondate, TIMESTAMP)) = 2015
于 2015-07-07T06:08:15.063 回答