以下代码提供输出
CODE:
select a.AccountNumber,a.customername,sum (a. AverageBalance) AverageBalance,
b.Staff_ID,Period, a.Product, b.Branch_Code
from BubbleArchive a, Team b
where a.Bubble_Code= b.Officer_Code and a.year = 2013 and a.Year= b.Year
and Category = 'toys'
and (len(Staff_ID)<5 or Staff_ID like '%00')
group by a.AccountNumber,a.customername, b.Staff_ID,Period,a.Product,b.Branch_Code
order by AverageBalance desc
输出:
#AccountNumber #customername #AverageBalance #Staff_ID #Period #Caption #Branch_Code #
_________________________________________________________________________________________
#126 #OKOYEO #78806314 #1059 #1 #Cars #1 #
#384 #AGWUFEl #20135548 #5425 #1 #Skate #1 #
#504 #UCHENDUG #15730000 #5425 #1 #Xtra #1 #
#834 #ARINZEE #10058370 #5425 #2 #Xtra #1 #
#1068 #EMMANNUElE #7795364 #5425 #3 #Boat #1 #
#1099 #UMUDU #7548387 #5681 #1 #Xtra #2 #
#1109 #ROKA #7424560 #5425 #1 #Cars #1 #
#1202 #AlBERT #7104167 #5425 #4 #Xtra #2 #
#2326 #NWANNAHJ #6779029 #5425 #1 #Xtra #1 #
#2591 #ROCK #5000000 #5425 #5 #Boat #3 #
#2852 #NWOKOCHAC #4813380 #5425 #6 #Xtra #1 #
#2948 #ARISAV #4103225 #5808 #1 #Xtra #1 #
#3330 #NWAIMOI #4032209 #1059 #1 #Xtra #4 #
我想根据各自的平均余额(#AverageBalance)分别为每个月(#Period)和每个分支(#Branch_Code)选择前2名客户
答案 0 :(得分:2)
试试这个:
对于 SQL SERVER ::
SELECT *
FROM (SELECT ROW_NUMBER() OVER (ORDER BY AccountNumber, AverageBalance DESC PARTITION BY Period, Branch_Code) rowNo, *
FROM (SELECT a.AccountNumber,a.customername,SUM (a.AverageBalance) AverageBalance,
b.Staff_ID,Period, a.Product, b.Branch_Code
FROM BubbleArchive a, Team b
WHERE a.Bubble_Code= b.Officer_Code AND a.year = 2013 AND a.Year= b.Year AND
Category = 'toys' AND (len(Staff_ID)<5 OR Staff_ID LIKE '%00')
GROUP BY a.AccountNumber,a.customername, b.Staff_ID,Period,a.Product,b.Branch_Code
ORDER BY AverageBalance DESC
) AS A
) AS A
WHERE rowNo <= 2
答案 1 :(得分:1)
SELECT *
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY Period, Branch_Code ORDER BY AverageBalance DESC ) numofrows, *
FROM (SELECT a.AccountNumber,a.customername,SUM (a.AverageBalance) AverageBalance,
b.Staff_ID,Period, a.Product, b.Branch_Code
FROM BubbleArchive a, Team b
WHERE a.Bubble_Code= b.Officer_Code AND a.year = 2013 AND a.Year= b.Year
AND Category = 'toys'
AND (len(Staff_ID)<5 OR Staff_ID LIKE '%00')
GROUP BY a.AccountNumber,a.customername, b.Staff_ID,Period,a.Product,b.Branch_Code
ORDER BY AverageBalance DESC
) AS Temp
) AS Temp
WHERE numofrows < 3