我有以下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
的解决方法?
答案 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';
此外:
WHERE
代替HAVING
date_trunc('month', p.log_date)
而不是to_char
和extract
答案 3 :(得分:1)
Having
用于聚合函数条件,但是您不需要使用它,因为to_char
和extract
是正常函数。
我认为您忘记了使用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