473,804 Members | 2,101 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SQL: how to display top 5 then sum the rest

Hello,

I would like to query the top 5 best companies' sales (total sales),
then total the rest, what is the quickest and effective SQL to query
it?
Thanks in advance

Apr 6 '06 #1
8 16347
sw**********@ya hoo.com wrote:
Hello,

I would like to query the top 5 best companies' sales (total sales),
then total the rest, what is the quickest and effective SQL to query
it?
Thanks in advance


Please include DDL and sample data so that we don't have to guess at
your requirements. Here's my untested guess:

SELECT T.company_id, SUM(sale_amt) AS sale_amt
FROM sales AS S
LEFT JOIN
(SELECT TOP 5 WITH TIES company_id
FROM sales
GROUP BY company_id
ORDER BY SUM(sale_amt) DESC) AS T
ON S.company_id = T.company_id
GROUP BY T.company_id ;

--
David Portas, SQL Server MVP

Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.

SQL Server Books Online:
http://msdn2.microsoft.com/library/m...S,SQL.90).aspx
--

Apr 6 '06 #2
Thanks. Is "WITH TIES" a build in function, I can't get this working

Apr 6 '06 #3
sw**********@ya hoo.com wrote:
Thanks. Is "WITH TIES" a build in function, I can't get this working


It is in 7.0/2000/2005.

Always tell us what version you are using.

What does "can't get this working" mean? Error message? Wrong result?
Please post some code to reproduce the problem.

--
David Portas, SQL Server MVP

Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.

SQL Server Books Online:
http://msdn2.microsoft.com/library/m...S,SQL.90).aspx
--

Apr 6 '06 #4
OLAP.

Apr 6 '06 #5
It ran ok if I am just running only the middle part

SELECT TOP 5 WITH TIES company_id
FROM sales
GROUP BY company_id
ORDER BY SUM(sale_amt) DESC

But if I ran the whole query, it gave me Invalid column name
'WITHTIES', for some reason, WithTies became one word when I ran it.

Apr 7 '06 #6
Actually, I figure out "WITH TIES" isn't the function that I am looking
at.

Let me explain my scenario again. I want to see the top 5 compies'
sales, but any other companies' sales total with be sum up to a
category called "Other"

e.g.
Company Total Sales
Co. 1 $200
Co. 2 $150
Co. 3 $120
Co. 4 $100
Co. 5 $90
Other $900

Apr 7 '06 #7
Actually, I tried the SQL and I think it does work as desired. You
don't get a pretty label of "Other" for the sum of everything else, but
it works as advertised. I am not familiar with the "WITH TIES" syntax
either, so I was curious and tried it in Northwind:

SELECT T.ProductID, SUM(Quantity)
FROM [Order Details] D1
LEFT JOIN (SELECT TOP 5 WITH TIES ProductID
FROM [Order Details]
GROUP BY ProductID
ORDER BY SUM(Quantity) DESC) AS T
ON D1.ProductID = T.ProductID
GROUP BY T.ProductID
ORDER BY SUM(Quantity) DESC
ORDER BY T.ProductID

The above returned a list of 6 records. 5 with product ID's and the
sum of their quantity, and another row with no value for ProductID and
a sum of the quantity for all of those. If you do

select TOP 5 ProductID, SUM(Quantity)
from [Order Details]
group by ProductID
order by ProductID

you'll see the same 5 records that get returned in the first query.
Pretty slick actually. Anyway, I thought it might help you test it if
you had an example from a table you can get to.

I ran this in Query Analyzer vers 8.00.194 and I'm connecting to a
server version Microsoft SQL Server 2000 - 8.00.760. I didn't
experience the problem you had with the words "WITH TIES" getting
merged into one word.

Hope it helps,
Teresa Masino

Apr 7 '06 #8
Hi

Here is a slight modication to Davids SQL statement which with my sample
data results in the following, Note that CompanyNames are included and
'Other' appears at the bottom of the list.

Run on SQL 2000.

companyid CompanyName Amount
----------- -------------------- ---------------
3 Company 3 55599.83
5 Company 5 55468.11
1 Company 1 54803.95
10 Company 10 53781.68
8 Company 8 51504.47
NULL Other 235368.75
Create Table Companies(Compa nyID int not null Primary Key,
CompanyName varchar(20))

Create Table CompanySales(Ro wID int not null identity(1,1) Primary Key,
CompanyID int references Companies(Compa nyID),
Date SmallDatetime,
Amount decimal(18,2))
insert Companies values(1,'Compa ny 1')
insert Companies values(2,'Compa ny 2')
insert Companies values(3,'Compa ny 3')
insert Companies values(4,'Compa ny 4')
insert Companies values(5,'Compa ny 5')
insert Companies values(6,'Compa ny 6')
insert Companies values(7,'Compa ny 7')
insert Companies values(8,'Compa ny 8')
insert Companies values(9,'Compa ny 9')
insert Companies values(10,'Comp any 10')
Declare @Counter int
Declare @Co int
Declare @dt SmallDateTime
Declare @amt Decimal(18,2)

set @Counter = 1
while @Counter <> 1000
begin
set @Co = 1 + (rand() * 10.0)
set @dt = cast('1/1/2006' as smalldatetime) + (rand() * 365)
set @amt = 1 + rand() * 1000
insert CompanySales(Co mpanyID, Date, Amount) values (@Co, @Dt,@Amt)
set @Counter = @Counter + 1
end

SELECT T.companyid, coalesce(c.comp anyname,'Other' ) as CompanyName,
SUM(Amount) AS Amount
FROM CompanySales AS S
LEFT JOIN
(SELECT TOP 5 WITH TIES companyid
FROM CompanySales
GROUP BY companyid
ORDER BY SUM(Amount) DESC) AS T
ON S.companyid = T.companyid
left join Companies c
on t.companyid = c.companyid
GROUP BY T.companyid, c.companyName
order by case when t.companyid is null then 1 else 0 end, sum(Amount) desc

--
-Dick Christoph
dc******@mn.rr. com
612-724-9282
"David Portas" <RE************ *************** *@acm.org> wrote in message
news:11******** *************@v 46g2000cwv.goog legroups.com...
sw**********@ya hoo.com wrote:
Hello,

I would like to query the top 5 best companies' sales (total sales),
then total the rest, what is the quickest and effective SQL to query
it?
Thanks in advance


Please include DDL and sample data so that we don't have to guess at
your requirements. Here's my untested guess:

SELECT T.company_id, SUM(sale_amt) AS sale_amt
FROM sales AS S
LEFT JOIN
(SELECT TOP 5 WITH TIES company_id
FROM sales
GROUP BY company_id
ORDER BY SUM(sale_amt) DESC) AS T
ON S.company_id = T.company_id
GROUP BY T.company_id ;

--
David Portas, SQL Server MVP

Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.

SQL Server Books Online:
http://msdn2.microsoft.com/library/m...S,SQL.90).aspx
--

Apr 7 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
42039
by: Willem | last post by:
Hello I am quite hopeless and of course a newbe. The situation: Sql2k / query I would like it ot break down the following string: 2004 Inventory:Ex.Plant Farm1:1st Cut:Premium:0094
1
6178
by: Jeff Blee | last post by:
I hope someone can help me get this graph outputing in proper order. After help from Tom, I got a graph to display output from the previous 12 months and include the average of that output all in the one graph. The output was in the order of the months, but after unioning with the averages SQL code, the order is lost. Below is the full sql code that is the data source for the graph: SELECT (Format(.,"mmm"" '""yy")) AS Month,...
1
4823
by: vic pahilan | last post by:
hi, pls need help. I need to upload excel field to sql server field. the user will choose excel file then i will show the fields inside that excel file then copy it into sql server field. I already done the rest but I dont know how to start coding with the command to upload. i use the listview control for excel same with for sql server to display their fields. hope u can help. tnx n advance
3
2575
by: Hrvoje Vrbanc | last post by:
Hello all! Scenario: - web server at one location (domain) with VS 2003 - SQL server at a remote location (domain) - VPN connection on port 1433 between the two domains I have no troubles reaching the remote SQL server either from SQL Enterprise manager or in VS 2003 design-time (using the SQL authentication in both cases) - all the connections work and I can preview data while building
6
2138
by: Twobridge | last post by:
I hope someone can help me out with my problem. I have found a sql statement that basically pulls all bills filed within a certain time period and the payments made on those bills with in the same time period. I group the payments by payment year and filed year which gives me a matrix with the filed year as the row and the pay year as the column....and this appears fine. My problem is that my employer does not want to see the...
0
3342
debasisdas
by: debasisdas | last post by:
SAMPLE EXAMPLE TO SHOW USE OF PROCEDURE WITH IN MODE ===================================================== CREATE OR REPLACE PROCEDURE REVNUM (NUM NUMBER) IS REV INTEGER; NUM1 NUMBER; BEGIN NUM1:=NUM; REV:=0;
5
1798
by: brendan.mcgrath | last post by:
Hi All DB - SQL Express 2005 ST - ASP VBScript Dev Env OS - Win XP IIS5 I am trying to retrieve records from the DB and write them into a csv file/display onscreen for further processing. What is happening is the records are retrieved but when I write them into the file or display them on screen only the first and ninth fields display (fAddress1 &
1
3209
by: rasmidas | last post by:
Hi, I have written a shell script, in which I am connecting to the oracle database and doing some manipulation. while I am running the script, its showing me the messages I am displaying in the script as well the Oracle messages. But I dont want to display the oracle messages. Please let me know how to do this. Here I am pasting the output dpdcs5:/home/rd31424/DBAScript $ ./newAdmMenu.sh Enter the connect string :...
1
9597
ssnaik84
by: ssnaik84 | last post by:
Hi Guys, Last year I got a chance to work with R&D team, which was working on DB scripts conversion.. Though there is migration tool available, it converts only tables and constraints.. Rest of things (stored procedures, functions).. we have to manually edit. That time, we face some interesting challenges.. I failed to document all of them, but whatever I can share with u.. I will try.. :) ...
0
9714
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9594
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10600
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10350
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10351
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7638
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6866
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3834
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.