dbTalk Databases Forums  

Sum Only Top 20 Customers?

comp.databases.ms-sqlserver comp.databases.ms-sqlserver


Discuss Sum Only Top 20 Customers? in the comp.databases.ms-sqlserver forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
LightBulb
 
Posts: n/a

Default Sum Only Top 20 Customers? - 02-03-2010 , 03:25 PM






Hi...I need to return the Top 20 customers by 'Accounts Receivable
Balance' (= FutureBal + Per1Bal + ... + Per5Bal + Misc_Creds +
Unapplied) in the and then in the select list sum a calculated value,
Sum(Val1 -Val), and another. I am stuck on how to use TOP in a WHERE
Clause.. TIA LB

Reply With Quote
  #2  
Old   
Plamen Ratchev
 
Posts: n/a

Default Re: Sum Only Top 20 Customers? - 02-03-2010 , 04:35 PM






Here are two solutions:

SELECT SUM(<column>) AS total
FROM (
SELECT TOP 20 <columns>
FROM Table
ORDER BY <expression>) AS T;

SELECT SUM(<column>) AS total
FROM (
SELECT <columns>,
ROW_NUMBER() OVER(ORDER BY <expression>) AS rk
FROM Table) AS T
WHERE rk <= 20;

--
Plamen Ratchev
http://www.SQLStudio.com

Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.