2017-07-11 28 views
1

我在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 

也許我過於複雜了,所以我會非常感謝任何建議。

+1

你的問題的要求是你必須在查詢什麼不同。你說你想看到僅在2016年和2017年的價值,但你的過濾器是在2007年?真令人困惑。考慮添加樣本數據並從樣本中得到您想要的結果。 –

+0

@JorgeCampos謝謝豪爾赫,我沒有意識到我仍在搜索2007年,我會添加一個數據樣本和所需的結果。 – Dave

回答

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 
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 
相關問題