2014-09-26 50 views
0

我對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 

我想要按年份分組的最高值。如果我在一年之前完成一個團隊,我會得到一些答案,但我不能包含/顯示客戶羣(呃)。它只顯示年份和最大銷售額。當我包含客戶細分時,它給了我一張顯示所有銷售額的表格 - 而不是我要找的東西。我只想要那些包含MAX年銷售額(行情)和客戶細分(custseg)的行。對於什麼是值得這裏是我用來創建上面的代碼:

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; 

回答

0

假設所有領域都在爲這個問題所描述的客戶表,下面的查詢會做你想要什麼:

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 
    ); 

如果您不打算任意解決關係,請用右外部連接替換內部連接。使用CTE當

順便說一句,上面的查詢看起來更易讀:

0

我會使用ROW_NUMBER()

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; 
相關問題