How to sort specific column when using GROUPING SETS in SQL Server?

If I remember correctly, in SQL Server, it is not recommended to use "ORDER BY" when there's already a GROUP BY GROUPING SETS.
I have two columns: [UPC#] & [Description] both are varchar.
My grouping sets is like this:
GROUP BY
GROUPING SETS
([UPC],[Description])
I don't have 'ORDER BY' but it's automatically sorting the Description column.
If I added a 3rd column, sum(Qty), then it doesn't sort by Description anymore. But if I added
ORDER BY [Description]
then the grand total of sum(Qty) will be at the first row instead of the last.
Is there a way to sort the Description column and still let the grand total of sum(Qty) be at the last row instead?
Thanks.

Yes, it works.
Thank you.
Could you kindly explain the logic?
I don't quite understand the "= 3 THEN 1 ELSE 0" part.
Is the #3 mean the column index 3?
GROUPING_ID returns a bit mask value depending on number of columns grouped in the result 
So when you do GROUPING_ID(([UPC]),([Description]))
it has two columns UPC and Description so bit mask will be as follows
0 ie 00 for rows grouped by both UPC and Description fields
1 ie 01 for rows grouped by UPC ie UPC subtotals
2 ie 10 for rows grouped by Description ie Description subtotals
3 ie 11 for rows not grouped by both columns ie Grand total
see
http://msdn.microsoft.com/en-IN/library/bb510624.aspx
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Similar Messages

  • Isse with using Grouping Sets in SQL Server 2008 R2

    Hi,
    I created a query in SQL Server 2012 using grouping sets that works fine.  When I try to use the same query in SQL Server 2008 I get an error ("Inccorrect syntax near SETS").
    I researched using grouping sets in 2008 and didn't see any issue with my query.  What is different in grouping sets 2008 vs 2012?
    SELECT tl.ClientRegionCd as [Client Region Code] , tl.ClientRegionDesc as [Region Name], count(tl.CompleteICN) as [Trauma Letters Sent]
    from TORT_Trauma_Letters tl
    Where CONVERT(VARCHAR(26), tl.SecondNoticeSent, 23) between '2014-06-12' and '2014-06-12'
    GROUP BY GROUPING SETS((tl.ClientRegionCd, tl.ClientRegionDesc), ())
    Stacie

    Check this blog post as how to deal with date ranges
    http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/16/bad-habits-to-kick-mishandling-date-range-queries.aspx
    For your result you can simply achieve your result with UNION ALL, e.g.
    select Client, Region, Letters
    from myTable 
    UNION ALL
    select NULL, NULL, SUM(letters) as Letters
    For every expert, there is an equal and opposite expert. - Becker's Law
    My blog
    My TechNet articles

  • Error when using Oracle Migration WorkBench (Sql Server 2k to Oracle 8i)

    I'm trying to migrate a Sql Server 2k database to an Oracle 8i schema using OMWB. After using BCP to collect metadata information on the source database, I tried to capture the source data model and got a "Capture aborted" message on the progress screen (even though then it appears a dialog window reporting "0 errors and 0 warnings", funny!). Down there is the error log OMWB generated. After reading some posts, I changed some columns of the OMWB dictionary that holds the source database name, but still got the same error. If someone can enlighten me on this toppic, I'd greatly appreciated it.
    Here's the error log of OMWB:
    ** Oracle Migration Workbench
    ** Production
    ** ( Build 20050629 )
    ** OMWB_HOME: D:\Datos\Download\Oracle\Oracle Migration Workbench\omwb
    ** user language: es
    ** user region: null
    ** user timezone:
    ** file encoding: Cp1252
    ** java version: 1.4.2_04
    ** java vendor: Sun Microsystems Inc.
    ** o.s. arch: x86
    ** o.s. name: Windows 2000
    ** o.s. version: 5.0
    ** Classpath:
    ..\lib\boot.jar
    ** Started : Fri Feb 23 17:18:48 GMT-03:00 2007
    ** Workbench Repository : Oracle8i Enterprise Edition Release 8.1.6.0.0 - Production
    With the Partitioning option
    JServer Release 8.1.6.0.0 - Production
    Repository Connection URL: jdbc:oracle:thin:@ServerCms:1521:sigcewbc
    ** The following plugins are installed:
    ** Microsoft Access 2.0/95/97/2000/2002/2003 Plugin, Production Release 10.1.0.4.0
    ** Microsoft SQLServer 2000 Plugin, Production Release 10.1.0.4.0
    ** Microsoft SQLServer 6.5 Plugin, Production Release 10.1.0.4.0
    ** Microsoft SQLServer 7.0 Plugin, Production Release 10.1.0.4.0
    ** Active Plugin : SQLServer2K
    EXCEPTION :SQLServer2KDisconnSourceModelLoad.loadSourceModel(): oracle.mtg.migration.MigrationStopException: java.lang.IndexOutOfBoundsException: Index: 15, Size: 15
    ** Shutdown : Fri Feb 23 18:00:50 GMT-03:00 2007

    Duplicate thread
    Error when using Oracle Migration WorkBench (Sql Server 2k to Oracle 8i)

  • Want to sort the columns while using GROUP BY ROLLUP.

    Want to order the below query using by "News' column in descending order and "Email address" column in Ascending order.
    Note: Sorting should not bring Total value to top. It is happening now.
    {code}
    SELECT decode(grouping(NVL(Client, 'NA')),1, 'Totals', NVL(Client, 'NA')) "Email (Login ID)",
    Location "Location",
    SUM(News) "News",
    SUM(Website) "Website",
    FROM VW_FX_USERDATA
    GROUP BY ROLLUP (((NVL(Client, 'NA')),Location,1, 'Totals', NVL(Client, 'NA')))
    {code}
    PLease let me know if you need any details.
    Edited by: Nagaraja Akkivalli on Sep 23, 2011 4:04 PM

    Thanks hm,
    Let me explain bit clearly.
    Say I am getting resultset as below.When I am executing above mentioned query.
    Client*        Location    News      Website       Total
    ABC        YD           9     0           4
    BCD        HB           12     7           13
    CDE        SI            1     18           3
    JNM        BI          25     0           4
    ZZZ        TI          0     221           77
    XYZ        TT          0     1           1
    Totals                      47     247           435I want it to as below. Here records are sorted in the descending order of the News Count and then Client*
    Client*        Location    News      Website       Total
    JNM        BI          25     0           4
    BCD        HB           12     7           13
    ABC        YD           9     0           4
    CDE        SI            1     18           3
    XYZ        TT          0     1           1
    ZZZ        TI          0     221           77
    Totals                      47     247           435If I order the column by News in the descending order, it is taking Totals value to the top. (Since I am using GROUP BY ROLLUP).
    Note: Sorting should not be applied to Totals.
    Hope this is clear to you. Let me know if you need any details.
    Thanks and Regards
    Nagaraja Akkivalli.

  • VersioningError when Using JDBC driver for SQL Server with RMI

    Hi,
    I wrote a simple class for inserting rows into a database. The database is SQL Server 2000, and I am using weblogic's mssqlserver4 driver. The class works fine, but when I try to export the class as a remote object (using Sun's RMI implementation, not Weblogic RMI), I get the following error:
    Exception in thread "main" weblogic.common.internal.VersioningError: No WebLogic packages defined in CLASSPATH at weblogic.common.internal.VersionInfo.<init>(VersionInfo.java:35) at weblogic.version.<clinit>(version.java:18)
    at weblogic.jdbc.common.internal.FileProxy.initFileHandles(FileProxy.java:30) at weblogic.jdbc.mssqlserver4.BaseConnection.prepareConnection(BaseConnection.java:215)
    at weblogic.jdbc.mssqlserver4.Driver.newConnection(Driver.java:34) at weblogic.jdbc.mssqlserver4.ConnectDriver.connect(ConnectDriver.java:151) at java.sql.DriverManager.getConnection(DriverManager.java:512) at java.sql.DriverManager.getConnection(DriverManager.java:171)
    Can anyone tell me why this happens? What is difference between using the driver standalone and using it with RMI? Does it have anything to do with the fact that I'm using Javasoft RMI and not Weblogic RMI? I'm pretty sure I have the classpaths set up correctly.
    Thanks,
    Bo

    Bo Min Jiang wrote:
    Hi,
    I wrote a simple class for inserting rows into a database. The database is SQL Server 2000, and I am using weblogic's mssqlserver4 driver. The class works fine, but when I try to export the class as a remote object (using Sun's RMI implementation, not Weblogic RMI), I get the following error:
    Exception in thread "main" weblogic.common.internal.VersioningError: No WebLogic packages defined in CLASSPATH at weblogic.common.internal.VersionInfo.<init>(VersionInfo.java:35) at weblogic.version.<clinit>(version.java:18)
    at weblogic.jdbc.common.internal.FileProxy.initFileHandles(FileProxy.java:30) at weblogic.jdbc.mssqlserver4.BaseConnection.prepareConnection(BaseConnection.java:215)
    at weblogic.jdbc.mssqlserver4.Driver.newConnection(Driver.java:34) at weblogic.jdbc.mssqlserver4.ConnectDriver.connect(ConnectDriver.java:151) at java.sql.DriverManager.getConnection(DriverManager.java:512) at java.sql.DriverManager.getConnection(DriverManager.java:171)
    Can anyone tell me why this happens? What is difference between using the driver standalone and using it with RMI? Does it have anything to do with the fact that I'm using Javasoft RMI and not Weblogic RMI? I'm pretty sure I have the classpaths set up correctly.
    Thanks,
    BoHi. Show me the whole stacktrace of the exception. The issue seems to be the driver licensing
    code, which is looking for the bea.license file, and not finding it. Have your code run a System command
    to find and print out the classpath it thinks is in effect. You will then see if the license file is there.
    Joe

  • How to select the column with respect to language in sql server

    USE Master
    SELECT * FROM SysMessages
    GO
    when i execute the above query, in description column am getting English and Chinese , here if i want to select only English .
    how can i select only English language by using WHERE condition.
    And why am getting data in Description column in Chinese also any reason behind it.
    If there is any reason please suggest me.

    Bro , here am not getting what is Unicode and all
    Specially ,
    Why does we need N' string ' while inserting and Why we need to place N and String in Unicode while inserting data and what does it mean.
    Insert into T1 Values
    (N'找不到由給定的 @article 或 @artid ''%1!'' 所參考的物件。'),
    (N'Unclosed quotation mark after the character string .')

  • How to make muliple column listbox using indesign cs3

    Hi,    
         I want to create list box having muliple rows and columns. I tried with one cloumn using tree view and that is working fine. How to create multiple column listbox using tree view. I need a code snippet for muliple rows and columns using treeview.
    Thanks
    K.Saravanan

    Download the CS6 SDK. Under the "open" folder you will find the code for the LinksUI panel. This is the closest you will get to a multicolumn list box in C++, if you want to stay in C++.
    The tree view widget support dynamic load of sub nodes in a tree. Also it will only request widgets to drawn when they are in view (as far as I remember).

  • How to avoid data repetation when using select statements with innerjoin

    how to avoid data repetation when using select statements with innerjoin.
    thanks in advance,
    satheesh

    you can use a query like this...
      SELECT DISTINCT
             frg~prc_group1                  "Product Group 1
             frg~prc_group2                  "Product Group 2
             frg~prc_group3                  "Product Group 3
             frg~prc_group4                  "Product Group 4
             frg~prc_group5                  "Product Group 5
             prc~product_id                  "Product ID
             txt~short_text                  "Product Description
    UP TO 10 ROWS
    INTO TABLE l_i_data
    FROM
    Joining CRMM_PR_SALESG and
    COMM_PR_FRG_ROD
    crmm_pr_salesg AS frg
    INNER JOIN comm_pr_frg_rod AS prd
    ON frgfrg_guid = prdfragment_guid
    Joining COMM_PRODUCT and
    COMM_PR_FRG_ROD
    INNER JOIN comm_product AS prc
    ON prdproduct_guid = prcproduct_guid
    Joining COMM_PRSHTEXT and
    COMM_PR_FRG_ROD
    INNER JOIN comm_prshtext AS txt
    ON prdproduct_guid = txtproduct_guid
    WHERE frg~prc_group1 IN r_zprc_group1
       AND frg~prc_group2 IN r_zprc_group2
       AND frg~prc_group3 IN r_zprc_group3
       AND frg~prc_group4 IN r_zprc_group4
       AND frg~prc_group5 IN r_zprc_group5.
    reward it it helps
    Edited by: Apan Kumar Motilal on Jun 24, 2008 1:57 PM

  • How to solve power error when using USB camera adapter in your camera

    Hello Everyone,
    First of all I wanna say reducing the output of the USB camera adapter from 100mA to 20mA just to save battery life is by far the most incredible adjustment in the history of @)#*$#%*($#!
    I know most of us bought the USB Camera adapter so we can use it as a USB adapter for the Camera (saves us from taking the memory card on and off the camera) but sadly the "Ginues Apple" reduced it to 20mA which decreases the range of cameras and flash drives that will work with it. I use Gopro Hero 3+ black and everytime I plug it with the adapter to my ipad I keep on seeing this @#@$#@ power error. I didn't want to waste the expensive adapter so I tried to look for a micro sd card reader but I don't think 20mA readers still exist.
    Now to solve this problem is very simple add a power source to help that 20mA up, most of the my friends bought a powered port hub but it's not my type because it's bulky, needs an outlet and not portable.
    So I found a better solution on how you can add a power source and still be portable, the answer is power bank or portable charger.
    Things you need:
    Camera
    USB camera adapter (Ginues Apple product)
    Power bank (I'm using 8,400 mAh)
    Dual USB Male to 5 Pin Mini USB Y Cable
    Ipad
    Procedure:
    Camera --- 5 Pin Mini USB ------------------ USB camera adapter ---------- Ipad
                                                   '---------- Power Bank
    Attach you camera to the 5 pin mini usb then the USB1 male to the female apple's USB camera adapter then to the Ipad. = this will show the power error.
    Then attach the USB2 to the power bank/portable charger to power it up.
    your welcome

    yocto yotta wrote: How to charge iPad Air when using the camera connection kit?
    No can do, Skippy!

  • How to hide system tables when using the Oracle SQL Developer?

    Hi,
    I would like to know how can I show only the tables that I created under the Tables tree? I didnt find a way to create a separate database using the Oracle Sql Developer. I see all the tables together, and would like to differentiate between different databases.
    Can anyone explain to me how to do these things?
    Thanks,

    Hi,
    I would like to know how can I show only the tables that I created under the Tables tree? Your posting is not clear,again tell something more on tables tree,what u want to achieve with it.
    How to hide system tables when using the Oracle SQL Developer? if u connected with sys, system or user with dba role then u have a privilege to see these tables,so revoke the privilege/role from ur user to view this tables if ur connected other then sys,system,
    I didnt find a way to create a separate database using the Oracle Sql Developer. DBCA is a tool for creating the new database.
    Kuljeet

  • Ques;How  do you secure imail when used being used in iweb. People can mess

    How do you secure imail when used being used in iweb? People can mess w/my settings in iweb imail window.

    What is iMail?
    And what is an iWeb iMail window?
    iWeb is part of iLife 06 which is an application used to create websites hosted on .Mac.
    Are you referring to Apple's Mail application and webmail access using a browser such as Safari to access your .Mac account?
    Which people can mess with what settings? You shouldn't allow anyone else to access your Mac when logged in to your account and home folder/directory. OS X was designed for multiple users of the same Mac with each regular user having their own computer login account (with or without admin privileges) and associated home folder/directory to store and access their data and settings for their login account only.

  • Does anyone know how to load ACR presets when using ACR in the creative cloud?

    Does anyone know how to load ACR presets when using ACR in the creative cloud?

    Moving the discussion to Adobe Camera Raw forum.
    Thanks,
    Atul Saini

  • How to sync/edit audio when using frame freeze or time remapping?

    how to sync/edit audio when using frame freeze or time remapping? in premiere pro cs6

    You need to give more information about what you want to happen to the audio when you freeze or time remap the associated video.
    Is it synch video?
    Is it music?
    Is it Voice?
    Generally .. you have to cut and design the audio around the video effect.

  • How do I lock safesearch when using BING

    how do I lock safesearch when using BING search engine

    I assume you're using the "Content Aware" option for the Spot Healing brush.  It can be a maddeningly stupid option -- there's no telling from how far away it will pull the replacement pixels and will leave streaks that can be very difficult to remove.
    It would be best for you to include a sample image that's giving you the problem so we can suggest the best way to attack it.
    In general, the "Content Aware" option works best when you use a very small brush size.  That pulls in pixels closer to the area you want to heal.  If you get streaks, sometimes you can use the Spot Healing brush to get rid of them by going over the area in a perpendicular direction to the streaks.
    Ken

  • How to insert namespace prefix when using xmltype

    Hi,
    I have registered the following XML schema into XMLDB.
    <s:schema xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:m="https://suora.tietopalvelut.com/ATJkysely/" targetNamespace="https://suora.tietopalvelut.com/ATJkysely/" elementFormDefault="qualified" xdb:schemaURL="http://www.fennia.fi/Hae121.xsd">
         <s:element name="Hae" type="m:Hae121" xdb:SQLType="Hae121"/>
         <s:complexType name="Hae121" xdb:SQLType="Hae121" xdb:maintainDOM="false">
              <s:sequence>
                   <s:element name="kayttajatunnus" type="m:Kayttajatunnus" minOccurs="0" xdb:SQLName="kayttajatunnus" xdb:SQLType="Kayttajatunnus121" xdb:SQLInline="true"/>
                   <s:element name="palvelutunnus" type="s:string" minOccurs="0" xdb:SQLName="palvelutunnus" xdb:SQLType="VARCHAR2" xdb:SQLInline="true"/>
                   <s:element name="kyselylaji" type="s:string" minOccurs="0" xdb:SQLName="kyselylaji" xdb:SQLType="VARCHAR2" xdb:SQLInline="true"/>
                   <s:element name="rekisteritunnus" type="s:string" minOccurs="0" xdb:SQLName="rekisteritunnus" xdb:SQLType="VARCHAR2" xdb:SQLInline="true"/>
                   <s:element name="laji" type="s:string" minOccurs="0" xdb:SQLName="laji" xdb:SQLType="VARCHAR2" xdb:SQLInline="true"/>
                   <s:element name="ajoneuvoluokka" type="s:string" minOccurs="0" xdb:SQLName="ajoneuvoluokka" xdb:SQLType="VARCHAR2" xdb:SQLInline="true"/>
                   <s:element name="valmistenumero" type="s:string" minOccurs="0" xdb:SQLName="valmistenumero" xdb:SQLType="VARCHAR2" xdb:SQLInline="true"/>
                   <s:element name="jarjestelmatunnus" type="s:string" minOccurs="0" xdb:SQLName="jarjestelmatunnus" xdb:SQLType="VARCHAR2" xdb:SQLInline="true"/>
              </s:sequence>
         </s:complexType>
         <s:complexType name="Kayttajatunnus" xdb:SQLType="Kayttajatunnus121" xdb:maintainDOM="false">
              <s:sequence>
                   <s:element name="username" type="s:string" minOccurs="0" xdb:SQLName="username" xdb:SQLType="VARCHAR2" xdb:SQLInline="true"/>
                   <s:element name="password" type="s:string" minOccurs="0" xdb:SQLName="password" xdb:SQLType="VARCHAR2" xdb:SQLInline="true"/>
                   <s:element name="statcode" type="s:string" minOccurs="0" xdb:SQLName="statcode" xdb:SQLType="VARCHAR2" xdb:SQLInline="true"/>
                   <s:element name="enduserid" type="s:string" minOccurs="0" xdb:SQLName="enduserid" xdb:SQLType="VARCHAR2" xdb:SQLInline="true"/>
                   <s:element name="timestamp" type="s:string" minOccurs="0" xdb:SQLName="timestamp" xdb:SQLType="VARCHAR2" xdb:SQLInline="true"/>
                   <s:element name="checksum" type="s:string" minOccurs="0" xdb:SQLName="checksum" xdb:SQLType="VARCHAR2" xdb:SQLInline="true"/>
                   <s:element name="ticket" type="s:string" minOccurs="0" xdb:SQLName="ticket" xdb:SQLType="VARCHAR2" xdb:SQLInline="true"/>
              </s:sequence>
         </s:complexType>
    </s:schema>
    In PL/SQL I populate the object types, which have been automatically generated.
    Then I create an XMLTYPE object using the following code:
    akeobject "Hae121";
    v_schema VARCHAR2 (1000) := 'http://www.fennia.fi/Hae121.xsd';
    v_schema_element VARCHAR2 (100) := 'Hae';
    --akeobject populated here
    v_xml_out := XMLTYPE (akeobject, v_schema, v_schema_element);
    DBMS_OUTPUT.put_line ('v_xml_out:' || v_xml_out.getstringval ()) shows the following:
    <Hae xmlns="https://suora.tietopalvelut.com/ATJkysely/">
    <kayttajatunnus>
    <username>kayttaja</username>
    <password>salasana</password>
    <statcode>tiltunn</statcode>
    <enduserid>loppukay</enduserid>
    <timestamp>20060822100700</timestamp>
    <checksum>E77B30394D23F83D422A63027F8F63A8</checksum>
    <ticket>nyckkeli</ticket>
    </kayttajatunnus>
    <palvelutunnus>PALVELUTUNNUS</palvelutunnus>
    <kyselylaji>41</kyselylaji>
    <rekisteritunnus>BRF-444</rekisteritunnus>
    <ajoneuvoluokka>1</ajoneuvoluokka>
    <valmistenumero>BBBB</valmistenumero>
    <jarjestelmatunnus>AAAA</jarjestelmatunnus>
    </Hae>
    There are no namespace prefixes.
    When I create a model XML file using XMLSpy, I get the following:
    <?xml version="1.0" encoding="UTF-8"?>
    <!--Sample XML file generated by XMLSpy v2007 rel. 3 sp1 (http://www.altova.com)-->
    <m:Hae xmlns:m="https://suora.tietopalvelut.com/ATJkysely/">
         <m:kayttajatunnus>
              <m:username>String</m:username>
              <m:password>String</m:password>
              <m:statcode>String</m:statcode>
              <m:enduserid>String</m:enduserid>
              <m:timestamp>String</m:timestamp>
              <m:checksum>String</m:checksum>
              <m:ticket>String</m:ticket>
         </m:kayttajatunnus>
         <m:palvelutunnus>String</m:palvelutunnus>
         <m:kyselylaji>String</m:kyselylaji>
         <m:rekisteritunnus>String</m:rekisteritunnus>
         <m:laji>String</m:laji>
         <m:ajoneuvoluokka>String</m:ajoneuvoluokka>
         <m:valmistenumero>String</m:valmistenumero>
         <m:jarjestelmatunnus>String</m:jarjestelmatunnus>
    </m:Hae>
    What am I doing wrong because there are no namespace prefixes when using XMLTYPE in PL/SQL?
    My environment is 10g 10.2.0.2.
    Thanks,
    Veli-Matti

    Hi ,
    >>>i removed namespace from source and target Message Type of message mapping but still getting "ns3" prefix. My requirement is to just have this ns3 removed.
    Which process you've used for removing namespace...java/xslt mapping. In case of java mapping plese remove ns3 while creating the target element. Please go through the below blog it may help you.
    Quick Tips: Dealing with Namespaces in XI/PI
    Regards,
    Priyanka

Maybe you are looking for