SQL PLUS仅返回列中最常见的值

时间:2018-03-18 19:12:40

标签: oracle sqlplus

SQL PLUS: 我试图返回最常见的“MAKE”#39;从一张桌子和' NAME'来自另一张桌子的顾客这就是我所拥有的:

 SELECT sv.make, c.first, c.MI, c.last
  FROM Sales s
   INNER JOIN Sale_Vehicles sv
    ON s.VIN = sv.VIN
   INNER JOIN Customers c
    ON s.cust_ID = c.cust_ID
  GROUP BY sv.make, c.first, c.MI, c.last
  ORDER BY sv.make, COUNT (*) DESC;

这会返回最常见的“MAKE”#39;在结果的顶部,第二个和第三个在它下方。我如何只返回最频繁的?

3 个答案:

答案 0 :(得分:0)

可以将结果用作rownum

的子选择检查
select * from ( 
 SELECT sv.make, c.first, c.MI, c.last
  FROM Sales s
   INNER JOIN Sale_Vehicles sv
    ON s.VIN = sv.VIN
   INNER JOIN Customers c
    ON s.cust_ID = c.cust_ID
  GROUP BY sv.make, c.first, c.MI, c.last
  ORDER BY sv.make, COUNT (*) DESC) T 
  where rownum =1

答案 1 :(得分:0)

如果您需要最频繁的MAKE(即COUNT是其中大部分的那个),您应首先按ORUNT BY COUNT,而不是MAKE。像这样:

SELECT *
FROM (SELECT sv.make, c.first, c.MI, c.last
     FROM Sales s
     INNER JOIN Sale_Vehicles sv
       ON s.VIN = sv.VIN
     INNER JOIN Customers c
       ON s.cust_ID = c.cust_ID
     GROUP BY sv.make, c.first, c.MI, c.last
     ORDER BY COUNT (*) DESC               --> different from your ORDER BY
    )
WHERE rownum = 1;

[编辑]

右;如果多个MAKE满足条件,那么RANK分析函数可能会有所帮助。以下是基于Scott的架构的示例:

工作频率:

SQL> select job, count(*)
  2  from emp
  3  group by job
  4  order by count(*) desc;

JOB         COUNT(*)
--------- ----------
CLERK              4
SALESMAN           4
MANAGER            3
ANALYST            2
PRESIDENT          1

让我们对它们进行排名:

SQL> select job, count(*),
  2    rank() over (order by count(*) desc) rn
  3  from emp
  4  group by job
  5  order by count(*) desc;

JOB         COUNT(*)         RN
--------- ---------- ----------
CLERK              4          1    --> these 2 should be returned as the 
SALESMAN           4          1    --> final result
MANAGER            3          3
ANALYST            2          4
PRESIDENT          1          5

最终结果:

SQL> select *
  2  from (select job, count(*), rank() over (order by count(*) desc) rn
  3        from emp
  4        group by job)
  5  where rn = 1;

JOB         COUNT(*)         RN
--------- ---------- ----------
CLERK              4          1
SALESMAN           4          1

应用于您的查询:

select *
  from (  select sv.make,
                 c.first,
                 c.mi,
                 c.last,
                 rank () over (order by count (*) desc) rn             --> new
            from sales s
                 inner join sale_vehicles sv on s.vin = sv.vin
                 inner join customers c on s.cust_id = c.cust_id
        group by sv.make,
                 c.first,
                 c.mi,
                 c.last)
 where rn = 1;

有什么改进吗?

答案 2 :(得分:0)

BINARY_ADD