【问题标题】:Determine which year-month has the highest and lowest value [duplicate]确定哪个年月的值最高和最低[重复]
【发布时间】:2021-11-12 03:08:20
【问题描述】:

这是我的第一个查询,显示每年每月新增的客户数量

select count(name) AS CUSTOMER, 
       extract(year from create_date) as yr, 
       extract(month from create_date) as mon
from x
group by extract(year from create_date), 
         extract(month from create_date)
order by yr desc, mon desc;
CUSTOMER YR MON
3 2019 07
4 2015 02
100 2014 09
3 2014 04

我试过查询

SELECT MAX(count(*))
FROM x
GROUP BY create_date;

在我得到的结果中;

MAX(COUNT(*))
100

需要查看结果中的年份和月份。

如何做到这一点?

【问题讨论】:

  • 您的问题有几个格式问题,但是,忽略这一点,您是否尝试过解析日期的年份和月份? to_number(to_char(create_date, 'YYYYMM')).

标签: sql oracle top-n


【解决方案1】:

按照我理解问题的方式,您将在子查询(或 CTE)中使用 rank 分析函数并获取计数为最小值或最大值的行。像这样的:

with temp as
  (select to_char(create_date, 'yyyymm') yyyy_mm,
          count(*) cnt,
          --
          rank() over (order by count(*)  asc) rnk_min,
          rank() over (order by count(*) desc) rnk_max
   from x
   group by to_char(create_date, 'yyyymm')
  )
select yyyy_mm,
       cnt
from temp
where rnk_min = 1
   or rnk_max = 1;

【讨论】:

  • "cnt" : 标识符无效
  • 没有了;忘记设置别名(第 3 行)。固定的;对不起。
【解决方案2】:

您可以使用两个级别的聚合并使用keep(实现“第一”聚合功能)将结果全部放在一行中:

select max(num_customers) as max_num_customers,
       max(yyyymm) keep (dense_rank first order by num_customers desc) as max_yyyymm,
       min(num_customers) as max_num_customers,
       max(yyyymm) keep (dense_rank first order by num_customers asc) as in_yyyymm,
from (select to_char(create_date, 'YYYY-MM') as yyyymm,
             count(*) AS num_customers
      from x
      group by to_char(create_date, 'YYYY-MM'
     ) ym

【讨论】:

    【解决方案3】:

    在 Oracle 12 中,您可以使用 FETCH FIRST ROW ONLY 来获取客户数量最多的行(如果是平局,则为最新日期):

    SELECT count(name) AS CUSTOMER,
           extract(year from create_date) as yr, 
           extract(month from create_date) as mon
    FROM   x
    GROUP BY
           extract(year from create_date), 
           extract(month from create_date)
    ORDER BY
           customer DESC,
           yr DESC,
           mon DESC
    FETCH FIRST ROW ONLY;
    

    如果您想为最多的客户添加领带,那么:

    SELECT count(name) AS CUSTOMER,
           extract(year from create_date) as yr, 
           extract(month from create_date) as mon
    FROM   x
    GROUP BY
           extract(year from create_date), 
           extract(month from create_date)
    ORDER BY
           customer DESC
    FETCH FIRST ROW WITH TIES;
    

    【讨论】:

      猜你喜欢
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      相关资源
      最近更新 更多