【问题标题】:What does the following query mean?以下查询是什么意思?
【发布时间】:2021-07-16 10:29:34
【问题描述】:

请参考以下用oracle编写的查询。谁能告诉我查询的含义?

select count(*) from dual connect by level <= 5
group by trunc(next_day(trunc(sysdate,'mm')-1, 'sunday') + (level -1)*7,'mm')

【问题讨论】:

    标签: sql oracle oracle11g


    【解决方案1】:

    如果您检查 group by 子句的部分返回,它是当月的第一天,计算结果为随后的第一个星期日:

    SQL> select trunc(sysdate, 'mm') trnc,
      2         next_day(trunc(sysdate, 'mm') - 1, 'sunday') ne_day
      3  from dual;
    
    TRNC       NE_DAY
    ---------- ----------
    01.04.2021 04.04.2021
               ^
               first Sunday in April 2021
    

    connect by 子句返回 5 行。哪个?当查询从 dual 中选择时,它只有一列 (dummy),其值为 'X',您不会看到太多。但是,如果您检查 group by 子句中的内容并选择这些值,您会得到

    SQL> select trunc(next_day(trunc(sysdate,'mm')-1, 'sunday') + (level -1)*7,'mm')
      2  from dual
      3  connect by level <= 5;
    
    TRUNC(NEXT
    ----------
    01.04.2021        --> 4 rows of 1st of April 2021
    01.04.2021
    01.04.2021
    01.04.2021
    01.05.2021        --> 1 row  of 5th of April 2021
    
    SQL>
    

    当您计算每个值的出现次数时(由于group by 子句),您发布的查询的最终结果是

    SQL> select count(*)
      2  from dual
      3  connect by level <= 5
      4  group by trunc(next_day(trunc(sysdate,'mm')-1, 'sunday') + (level -1)*7,'mm');
    
      COUNT(*)
    ----------
             1        --> that's for 5th of April 2021
             4        --> that's for 1st of April 2021
    
    SQL>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 1970-01-01
      • 2014-09-14
      • 2017-05-30
      • 2011-05-26
      • 2014-10-16
      相关资源
      最近更新 更多