【问题标题】:How to find values that are not shown in all years?如何找到所有年份都没有显示的值?
【发布时间】:2017-07-12 03:18:53
【问题描述】:

我在 Postgres 中有一个将近 14,000 行的表。我注意到某些年份存在但其他年份不存在的价值观。现在,我计算了 2017 年、2016 年、2015 年、2014 年等这些特定列中的值。我只是想让自己更容易选择仅在 2016 年和 2017 年出现的值,而不是其他年份的值。

例如:我在 2016 年和 2017 年找到“13HAZ02”;“Housekeeping”作为类型和描述。

我是这样数的:

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

我添加了一个 where not 但我没有正确使用它。我收到此错误:日期/时间字段值超出范围。

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

也许我过于复杂了,所以我非常感谢任何建议。

【问题讨论】:

  • 您的问题要求与您在查询中的要求不同。您说您想查看仅在 2016 年和 2017 年的值,但您的过滤器是 2007 年?真的很混乱。考虑添加样本数据并从样本中获得您想要的结果。
  • @JorgeCampos 感谢 Jorge,我没有意识到我仍在搜索 2007 年,我将添加数据样本和所需结果。

标签: postgresql


【解决方案1】:
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

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      相关资源
      最近更新 更多