.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Query to return TOP n with 'Other' grouping for all remaining rows

Posted By:      Posted Date: September 14, 2010    Points: 0   Category :Sql Server
Hi all, I've been given a specific type of report to produce, and am having difficulty in getting my SQL right to return the data as needed. I need to return TOP n Categories based on amount of sales (which I can do) but then a final category with a sum of all other sales. The purpose would be to capture all of the small sales values into one 'Other' category so that the chart I'll produce does not have lots and lots of small-value columns. I found the following post which seems to come close: SELECT TOP 10 CompanyID, CompanyName, SUM(GrossSales) [GrossSales] FROM CompanySales GROUP BY CompanyID, CompanyName ORDER BY SUM(GrossSales) desc UNION SELECT -1, 'Other' [CompanyName], SUM(GrossSales) [GrossSales] FROM CompanySales WHERE CompanyID NOT IN ( SELECT TOP 10 CompanyID, CompanyName, SUM(GrossSales) [GrossSales] FROM CompanySales GROUP BY CompanyID, CompanyName ORDER BY SUM(GrossSales) desc ) But this gives a syntax error on UNION, which I'm guessing is due to the ORDER BY clauses. However I think the ORDER BY is needed to ensure I return the results in the correct order. Does anyone have any ideas of how to do this? Thanks for any assistance Matt

View Complete Post

More Related Resource Links

function or query to return continuous span of months $ years as rows in query



I am using SS2008.

There are many situations in which I need to return a table where the rows are EVERY calendar month between two dates, not just the months where there is data present.

Is there a function that would take a beginning and end date mmddyyyy which would do this?

For example if I wanted 1/2004 through 8/2010?




and so on to





Thanks in advance,




MS SQL Server: Search All Tables, Columns & Rows For Data or Keyword Query

If you need to search your entire database for specific data, this query will come in handy.

So when a client needs a custom report or some sort of custom development using Great Plains, most of the time I will have to track down the data in the system by running this query and find the table(s) it is in.

Suppress Blank Rows in Grouping on SRS

I have a Table on a SRS report.  Within that Table I have a Group. I display Rows from the DataSet in the Group Header.  In the Detail Line of the Group, I display rows if a condition is true.  That condition is in the Filter Criteria (Fields!GroupID.Value > 0).  If the GroupID equals 0, I want to suppress the detail line.  If GroupID is greater than 0, I want to show it.  This works great in development mode within Visual Studio 2005. I deploy to SRS on our Test Server and run the report. All of the detail rows are displayed even the ones where GroupID = 0. I am using the same Data Source.  The only difference is running the report within Visual Studio and the SRS web site. Does anyone have a suggestion.  

return only rows - no columns

Hi all, I'm using the below query to retrieve one vendor information. I dont want the columns and I need the query to return me one row with no column header. what would be the syntax for that. I'm trying to use this on SAP BW system - if that really matters. I tried tweaking the code, but SAP didnt seem to like it and the error message isnt helpful either. The code below works just fine - but I want to get rid of the column header SELECT [Measures].MEMBERS ON COLUMNS, NON EMPTY [0VENDOR].[LEVEL01].MEMBERS DIMENSION PROPERTIES [0VENDOR].[20VENDOR] ON ROWS FROM [OPOMCHS0/ZQT_GPO_PO_CHNG_REP_SUMM_3]WHERE[0VENDOR].[ABCD] Please help. Thanks in advance.

Check if Linq query return result

HelloI have Linq query likeDim Prood= (From p InProdutcts _                                          where p.ProductID="InputInteger"                                                         ..... ) .SingleOrDefaultI could Use Count if I Use .ToList Instead of .SingleOrDefault , But now that I use 'SingleOrDefault', how Could I find if Prod contains any record or it's Empty.

Return default value from LINK query

I am using the  query listed below which includes multiple joins, in the result of the query I need to do some value replacement values Example: db.ASSETS.BUILDING_ID=300 that ID does not exist in db.BUILDINGS, in that case I need to return BUILDING_ID=0, db.BUILDINGS.NAME="Unassigned" Please help  var productQuery = from assets in db.ASSETs join relocatableUnits in db.UNITs on assets.UID equals Units.RUID into assets_units from Units in assets_units.DefaultIfEmpty() join build in db.BUILDINGs on assets.BUILDING_ID equals build.BUILDING_ID into assets_bins from build in assets_bins.DefaultIfEmpty() join test in db.TEST_SUITEs on assets.TEST_SUITE_ID equals test.TEST_SUITE_ID into test_bins from test in test_bins.DefaultIfEmpty() join testTrgt in db.TEST_SUITEs on assets.T_TEST_SUITE_ID equals testTrgt.T_SUITE_ID into testTrgt_bins from testTrgt in testTrgt_bins.DefaultIfEmpty()

MDX query to only return first row.

I have a given MDX query AND would like to only return a single row instead of the full result set. also I need to do this in a way so I can simple add a line to it without re-writting the entire statement. any suggestions how to do this? background: I running stored MDx queries against the cube using OPENQUERY. the result set I parse first to understand what is part of my dimension (not time) and what column defines the time so I can later on work with the results. any hekp is appreciated.

Returning rows not found in inner query

select * FROM [C_Accessioning].[HL7].[GMessages] where MessageID not in (Select MessageID from HL7.ORM_MSH) There are two rows of data in GMessages: MessageID MessageDateTime              Filename 28             2010-09-07 16:29:02.543    ORM1.hl7 29             2010-09-07 16:29:07.547    ORM2.hl7 There is no data in ORM_MSH. Please see sql statement copied above. The inner query returns null, I am expecting that the query return both rows from GMessages, but it does not return any rows. Please let me know how to fix.   Thanks,Deep

Return linq query in function

I try to return a var query from a function, but i'll get the error: Error:Error 41 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<System.Xml.XmlElement>'. An explicit conversion exists (are you missing a cast?)  Code: protected static IEnumerable<XmlElement> GetModels(byte MerkID) { string rawXML = AutoDisk.GetModels(12345, true, MerkID, "2010", ""); XmlDocument xml = new XmlDocument(); xml.LoadXml(rawXML); var query = from feed in xml.DocumentElement.ChildNodes.Cast<XmlNode>() select new { nModelID = feed.SelectSingleNode("nModelID").InnerText, Modelnaam = feed.SelectSingleNode("Modelnaam").InnerText }; return query; } Whats wrong and how can i make this working ?  

how to query return all data in Array Object ,Collection Object

how to query return all data in Array Object ,Hash Table ,And DataTable dataRowSelect * From Doc a

return rows with constant interval

what function should we use to return all alternate/ or rows that come after some constant number.   Please advice

Query returns correct rows but I am not able to concatenate the rows into a variable :(


Hi all,

Why in the code below I am able to list all rows and display the field 'stepID' but I am not able to concatenate them all in the variable @stepIds?

declare @date as datetime
set @date = '2010-09-20 23:01:20:000'
declare @instance as uniqueidentifier
set @instance = '04658F34-CBF1-4CCD-A683-F23BDB669D35'

  Declare @CrLf char(2)
  Set @CrLf = Char(13) + Char(10)
	Declare @stepIds varchar(8000)
	Set @stepIds = ''
		--@stepIds = @stepIds + ' - Step: ' + CONVERT(varchar(4), stepID)

How to return looped procedure results so that they display as multiple rows of a single output inst


I understand that the below fragment will return a separate 1-row results set for each successful loop (also unnecessarily repeating the column header each time). How can I alter my procedure so that each value returned by the loop is appended underneath the previous value as multiple rows of a single results set? Do I have to store each return value in a temp table or someother storage object? It would be nice to just be able to spit them out row by row as each loop returned. Possible? Easy? Hard? I really appreciate the help I've received here so far.

SELECT (whatever)

OPEN techCursor;
FETCH NEXT FROM techCursor INTO @techNumLoop;
EXECUTE pr_FindExpenses4Tech @techNumLoop, @itemCount OUTPUT
SELECT @itemCount Item_Count

Conditional insert: If select return rows, insert rows to table otherwise insert specific row indica

This is what I have

Insert into ReportDetail( Partcipantid, Reportid)  

select distinct ParticipantID , 9 from OpenCredit

      except select ParticipantID, 9 from StoreCredit where Closed = 0

 Issue is that when above select statement returns no row, it seems like no record is

One to many query: return most common value


I am working on a one to many query for an assets database.  Here is some sample data

Server Name        Application        Primary_User
Server1                 SQL                   DBA
Server1                 Citrix                 IT
Server1                 Oracle                DBA
Server2                 Sharepoint         Web
Server3                 SQL                   DBA
Server3                 Sharepoint         Web
Server3                 Norton               Security
Server3                 IDS                   Security

The desired output is one row per server with the server name, count of applications, and the Primary User that appears the most (not just the first, last, min, or max).

It would look like this

Server Name    Applications  Primary_User
Server1            3                  DBA
Server2            1                  Web
Server3            4                  Security

Is there a sub query that can accomplish this?  Thanks in advance!

Using SQL to return matches from 2 different bits of data in one query


Hi there,

i am writing a website that has a social networking element to it, and i want to display mutual friends of the person being viewed with the person that is viewing.

is it possible to search one database table and look for matching entries using 2 different usernames? if so how would i do it?

hope u can help,

many thanks

Query to return conditional counts both distinct and non distinct.


I have the following table structure:

Table EmailTracking



Table EmailTrackingDetail


The following query returns the default recordset:


SELECT     TOP (200) EmailTracking.EmailAddress, EmailTrackingDetail.TranType, EmailTrackingDetail.TranDate
FROM         EmailTracking INNER JOIN
                      EmailTrackingDetail ON EmailTracking.RecordID = EmailTrackingDetail.EmailTrackingRecordID







2010-09-21 16:59:29.980



2010-09-21 17:19:58.790



2010-09-27 12:00:30.940

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend