oracle 当select语句有不同的关键字时,使用count(1)= 1有什么用

a7qyws3x  于 2023-08-04  发布在  Oracle
关注(0)|答案(1)|浏览(139)

当select语句有不同的关键字并且只有一个列时,使用count(1)= 1有什么用?
查询如下所示:

select distinct (col1) 
FROM tab1
    where   creat_dt_tm >= sysdate - 1/24/60*30  and condition2 = "xyz" 
    group by col1,sys 
    having count(1) =1

字符串
这里的sys在group by子句中有什么用?
当我们对select语句应用distinct时,count(1)= 1有什么用?
我不知道我是否理解其中的逻辑。

lvjbypge

lvjbypge1#

我没有你的表,所以我将在Scott的emp示例表上说明它。
这是它的内容:

SQL> select deptno, empno, ename, job
  2  from emp
  3  order by deptno, job;

    DEPTNO      EMPNO ENAME      JOB
---------- ---------- ---------- ---------
        10       7934 MILLER     CLERK
        10       7782 CLARK      MANAGER
        10       7839 KING       PRESIDENT
        20       7788 SCOTT      ANALYST
        20       7902 FORD       ANALYST
        20       7876 ADAMS      CLERK
        20       7369 SMITH      CLERK
        20       7566 JONES      MANAGER
        30       7900 JAMES      CLERK
        30       7698 BLAKE      MANAGER
        30       7654 MARTIN     SALESMAN
        30       7521 WARD       SALESMAN
        30       7499 ALLEN      SALESMAN
        30       7844 TURNER     SALESMAN

14 rows selected.

SQL>

字符串
启动查询可能如下所示:deptnojob列的计数组合:

SQL> select deptno, job,         --> all non-aggregated columns ...
  2         count(*)
  3  from emp
  4  group by deptno, job        --> ... must be part of the GROUP BY clause
  5  order by deptno, job;

    DEPTNO JOB         COUNT(*)
---------- --------- ----------
        10 CLERK              1
        10 MANAGER            1
        10 PRESIDENT          1
        20 ANALYST            2
        20 CLERK              2
        20 MANAGER            1
        30 CLERK              1
        30 MANAGER            1
        30 SALESMAN           4

9 rows selected.

SQL>


现在,您的查询只想返回计数等于1的行,因此-让我们添加having子句:

SQL> select deptno, job, count(*)
  2  from emp
  3  group by deptno, job
  4  having count(*) = 1
  5  order by deptno, job;

    DEPTNO JOB         COUNT(*)
---------- --------- ----------
        10 CLERK              1
        10 MANAGER            1
        10 PRESIDENT          1
        20 MANAGER            1
        30 CLERK              1
        30 MANAGER            1

6 rows selected.

SQL>


查询作者决定不显示所有列,而只显示其中一列;在我的示例中,它将是job列(group by保持不变):

SQL> select job
  2  from emp
  3  group by deptno, job
  4  having count(*) = 1
  5  order by job;

JOB
---------
CLERK
CLERK
MANAGER
MANAGER
MANAGER
PRESIDENT

6 rows selected.

SQL>


显然,有重复,因此distinct关键字连同group by子句:

SQL> select distinct job
  2  from emp
  3  group by deptno, job
  4  having count(*) = 1
  5  order by job;

JOB
---------
CLERK
MANAGER
PRESIDENT

SQL>

相关问题