'group by ' 子句后的 'having' 错误

Error in 'having' after 'group by ' clause

我有以下 sql 查询:

SELECT
     to_char(p.log_date, 'Mon') as mon,
     extract(year from p.log_date) as year,
from
     T
group by
     mon
having
     mon = 'september'
and
     year = '2018';

table 的格式为:

date        col1     col2
2018/09/10   --       --
2018/09/11   --       --
2018/09/12   --       --

T 没有 monyear 列。 我收到错误 ERROR: column "mon" does not exist. 如何解决这个问题?

尝试以下 - 当您使用别名

时会发生这种情况
SELECT
     to_char(p.log_date, 'Mon') as mon,
     extract(year from p.log_date) as year
where to_char(p.log_date, 'Mon')= 'september'
and year = '2018';

使用 where 子句不需要 having

SELECT
     to_char(p.log_date, 'Mon') as mon,
     extract(year from p.log_date) as year from your_table
where  to_char(p.log_date, 'Mon') = 'september'
and
     extract(year from p.log_date) = '2018'

因为没有聚合函数所以这里不用想group by需要

mon 是你的列的别名,它在过滤器中找不到数据库引擎,所以它抛出错误。

注意:并非所有 dbms 都支持过滤器中的别名(where 或 having)

HAVING 子句中使用别名会导致问题。您可以在 HAVING(或 WHERE 子句)中使用 to_char 表达式。但是为了避免代码复制,您应该执行子查询或 CTE:

SELECT
     mon,
     year,
     ...
FROM (
    SELECT 
        to_char(p.log_date, 'Mon') as mon, 
        extract(year from p.log_date) as year,
        ... 
    FROM ...
)s
group by
     mon
having
     mon = 'september'
and
     year = '2018';

CTE:

WITH my_sub_query AS (
    SELECT 
        to_char(p.log_date, 'Mon') as mon, 
        extract(year from p.log_date) as year,
        ... 
    FROM ...
)
SELECT
     mon,
     year,
     ...
FROM my_sub_query
group by
     mon
having
     mon = 'september'
and
     year = '2018';

此外:

  1. 尝试使用 WHERE 而不是 HAVING
  2. 要按月和年分组,您可以 date_trunc('month', p.log_date) 而不是 to_charextract

Having用于聚合函数条件,但不需要使用它,因为to_charextract是普通函数。

我想你忘了使用 FROM 子句来 select 你的 table。

SELECT
     to_char(p.log_date, 'Mon') as mon,
     extract(year from p.log_date) as year,
FROM T
WHERE 
    to_char(p.log_date, 'Mon') = 'september'
AND
    extract(year from p.log_date) = '2018';

这很简单,试试这个。

Select mon, [year] from (
  SELECT
     to_char(p.log_date, 'Mon') as mon,
     extract(year from p.log_date) as year,
 from T

) as DerivedTable

 where  mon = 'september' and  year = '2018'

group by mon