在“ group by”子句之后“具有”时出错

时间:2018-10-24 08:55:17

标签: sql postgresql group-by where-clause having

我有以下sql查询:

page.c.Text="I found you";

表格的格式如下:

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';

T没有列date col1 col2 2018/09/10 -- -- 2018/09/11 -- -- 2018/09/12 -- -- mon。 我收到错误year的解决方法?

5 个答案:

答案 0 :(得分:2)

使用where子句不需要

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是您的列alis名称,在过滤器中找不到db引擎,因此抛出了错误。

注意:并非所有的dbms在过滤器中(位置或具有)都支持别名(别名)

答案 1 :(得分:1)

尝试以下操作-在使用别名时发生

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';

答案 2 :(得分:1)

HAVING子句中使用别名会导致此问题。您可以在to_char(或HAVING子句)中使用WHERE表达式。但是为了避免代码复制,您应该执行子查询或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

答案 3 :(得分:1)

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

我认为您忘记了使用FROM子句来选择表格。

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';

答案 4 :(得分:0)

这很简单,请尝试一下。

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