SQL查询最大和最小的数量

时间:2012-01-09 09:57:16

标签: sql max min

我有一个表Sales,其中包含以下字段:code, amount, index, name

我需要获得给定amount的最小和最大name,以及金额最小和最大的code

有人可以帮我构建查询吗?

3 个答案:

答案 0 :(得分:4)

如果您可以使用CTE和row_number()。

with S as 
(
  select Amount,
         Code,
         row_number() over(order by Amount asc) as rn1,
         row_number() over(order by Amount desc) as rn2
  from Sales
  where Name = 'SomeName'       
)
select SMin.Amount as MinAmount,
       SMin.Code as MinCode,
       SMax.Amount as MaxAmount,
       SMax.Code as MaxCode
from S as SMin
  cross join S as SMax
where SMin.rn1 = 1 and
      SMax.rn2 = 1

答案 1 :(得分:2)

要查找每个名称的最小和最大金额:

select
   name
   min(amount), max(amount)
from
  sales
group by name

并在单个查询中获取(最小和最大)和代码:

select *
from sales s
where 
       (amount = (select
                   max(s1.amount)
                 from sales s1
                 where  s1.name = s.name)
        or
        amount = (select
                   min(s2.amount)
                 from sales s2
                 where  s2.name = s.name)
       )

答案 2 :(得分:1)

假设这是Postgres,请尝试以下操作:

select name, 
       amount, 
       code,
       case when min_rank=max_rank then 'Minimum and Maximum'
            when min_rank=1 then 'Minimum'
            else 'Maximum'
       end as min_or_max
from
(select s.*,
        rank() over (partition by name order by amount) min_rank,
        rank() over (partition by name order by amount desc) max_rank
 from sales s) v
where 1 in (min_rank, max_rank)