如何检查最低数字列(PL SQL)

时间:2015-11-24 11:29:59

标签: oracle function plsql

返回购买汽车总数最多的邮政编码。由于可能存在两个或更多邮政编码的关系,因此请确保返回最低的数字邮政编码

表架构: enter image description here

CREATE OR replace FUNCTION Zip_code_sales_winner
  RETURN NUMBER
IS
  total NUMBER;
BEGIN
  SELECT max(y.[total purchases]) IN total
  FROM   (
                    SELECT     count(c.zip) AS 'Total Purchases'
                    FROM       customers c
                    inner join sales s
                    ON         c.cust_id=s.cust_id
                    inner join vehicles v
                    ON         s.vin=v.vin
                    GROUP BY   c.zip,
                               v.make) y;

  RETURN total;
END

问题是max可以返回多个值,我想只返回最低数字邮政编码的1个值。我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:1)

一个简单的选项是以二维方式按字典顺序排序,首先是按递减顺序的基于zip的计数,然后是通过增加邮政编码

SELECT z.tp
     , z.zip 
  INTO total
     , minzip
  FROM (
            SELECT y."Total purchases"    tp
                 , y.zip                  zip
              FROM (
                      SELECT     count(c.zip) AS "Total purchases"
                               , c.zip
                      FROM       customers c
                      inner join sales s
                      ON         c.cust_id=s.cust_id
                      inner join vehicles v
                      ON         s.vin=v.vin
                      GROUP BY   c.zip,
                                 v.make
                   ) y
          ORDER BY y."Total purchases" DESC
                 , y.zip               ASC
       ) z
 WHERE ROWNUM = 1              
     ;

答案 1 :(得分:0)

忘记我之前关于CeilFloor的帖子。他们在这里没有帮助。

您可以尝试使用另一个选择来确定您使用最大值查询的最小值(%值%)。

也许是这样的(未经测试):

CREATE OR replace FUNCTION Zip_code_sales_winner
  RETURN NUMBER
IS
  total NUMBER;
BEGIN
  SELECT min(x.Value) IN total from (
  SELECT max(y.[total purchases]) Value
  FROM   (
                    SELECT     count(c.zip) AS 'Total Purchases'
                    FROM       customers c
                    inner join sales s
                    ON         c.cust_id=s.cust_id
                    inner join vehicles v
                    ON         s.vin=v.vin
                    GROUP BY   c.zip,
                               v.make) y) x;

  RETURN total;
END

答案 2 :(得分:0)

您也可以使用分析函数对行进行排序并获取第一行。

如果你想要每个其他维度的极端行(例如每个销售人员),这种方法可以很好地扩展 - 在PARTITION BY函数中简单地添加ROW_NUMBER

with your_query as (
   ....
),
ordered_query as (
  select "Total purchases", zip,
  row_number() over (order by "Total purchases" desc, zip) as rn
  from your_query
)
select "Total purchases", zip
from ordered_query
where rn = 1