我在Postgres有一张几乎有14,000行的表。我注意到某些年份存在的价值,但在其他年份却没有。现在,我计算了2017年,2016年,2015年,2014年等特定列中的值。我只想让自己更容易选择仅在2016年和2017年的价值,而不是在其他年份。
例如:我在2016年和2017年发现了“13HAZ02”,“管家”作为类型和描述。
这就是我的计算方法:
select type, descr, count(*) as count
from (
select *
from table
where date >= '2016-01-01' and date <= '2016-12-31'
) as a
group by type, descr
order by count desc
我添加的地方没有,但我没有正确使用它。我收到此错误:日期/时间字段值超出范围。
select type, descr, count(*) as count
from (
select *
from table
where date >= '2016-01-01' and date <= '2016-12-31'
) as a
where not date > '2015-12-31'
group by type, descr
order by count desc
也许我过于复杂,所以我真的很感激任何建议。
答案 0 :(得分:0)
SELECT
a.type, a.descr, count(year) as count
FROM (
SELECT
type,
descr,
date_part(`year`, date) as year
FROM table
WHERE year > 2015 and year < 2018
) AS a
GROUP BY a.year
ORDER BY count DESC
答案 1 :(得分:0)
select
type, descr,
count(*) as count_total,
count(*) filter (where date >= '2016-01-01' and date <= '2016-12-31') as count_in_years
from table
group by type, descr
having count(*) = count(*) filter (where date >= '2016-01-01' and date <= '2016-12-31')
order by count desc