仅显示具有group by的列中的特定行

时间:2014-09-26 05:26:27

标签: sql oracle group-by oracle-sqldeveloper

我对Oracle SQL有些新意,无法解决这个问题。我想在第三列中显示具有高值的行。这是我正在使用的表:

theyear custseg     sales    
2010    Corporate   573637.62
2010    Home Office 515314.98
2010    Small Biz   390361.94
2010    Consumer    383825.67
2011    Corporate   731208
2011    Home Office 521274.34
2011    Consumer    390967.03
2011    Small Biz   273264.81
2012    Corporate   823861.38
2012    Consumer    480082.9
2012    Home Office 478106.93

我希望按年份分组的最高值。如果我只用一年做一组,我会得到一些答案,但我不能包括/显示客户群(呃)。它只显示年份和最大销售额。当我包含客户群时,它会给我一张表,显示所有销售 - 而不是我正在寻找的。我只想要包含给定年份(他们)和客户群(custseg)的MAX销售额的行。这里的价值是我用来创建上述代码的代码:

select theyear, custseg, max(totalsales) sales from (
select custseg, extract(year from ordshipdate) theyear, sum(ordsales) TotalSales from customers, orderdet
where customers.custid = orderdet.custid
group by custseg, extract(year from ordshipdate)
order by sum(ordsales) desc)
group by theyear, custseg
order by theyear, max(totalsales) desc;

2 个答案:

答案 0 :(得分:0)

假设所有字段都在问题中描述的customer表中,以下查询将执行您想要的操作:

select c.theyear, c.custseg, c.sales
from 
customer c inner join
(
  select theyear, max(sales) as max_sales_in_year
  from customer
  group by theyear
) maxvalues
on (
     c.year = maxvalues.theyear and
     c.sales = maxvalues.max_sales_in_year
   );

如果您不打算任意解决关系,请使用右外连接交换内连接。

答案 1 :(得分:0)

我会使用ROW_NUMBER():

SELECT theyear, custseg, totalsales FROM
(
 select theyear, custseg, totalsales, 
 ROW_NUMBER OVER(PARTITION BY theyear ORDER BY totalsales DESC) rn 
 from 
 (
  select custseg, extract(year from ordshipdate) theyear, sum(ordsales) TotalSales 
  from  customers, orderdet
  where customers.custid = orderdet.custid
  group by custseg, extract(year from ordshipdate)
 ) a
) b
WHERE rn = 1;

顺便说一下,使用CTE时,上面的查询看起来更具可读性:

WITH a AS(
select custseg, extract(year from ordshipdate) theyear, sum(ordsales) TotalSales 
from  customers, orderdet
where customers.custid = orderdet.custid
group by custseg, extract(year from ordshipdate)),
b AS (
select theyear, custseg, totalsales, 
ROW_NUMBER OVER(PARTITION BY theyear ORDER BY totalsales DESC) rn 
FROM a)
SELECT theyear, custseg, totalsales
FROM b;