SQL question for to get a top customer

Hi All,
I am prasanna. I have a question on SQL,to get a top customer based on year and customer name.I written query like this. But i got an error.
select calendar_year,cust_first_name,max(sum(amount_sold)) from sales,times,customers where sales.cust_id=customers.cust_id and times.time_id=sales.time_id group  by calendar_year,cust_first_name
The error is like this:
*Error starting at line 1 in command:
select calendar_year,cust_first_name,max(sum(amount_sold)) from sales,times,customers where sales.cust_id=customers.cust_id and times.time_id=sales.time_id group by calendar_year,cust_first_name
Error at Command Line:1 Column:7
Error report:
SQL Error: ORA-00937: not a single-group group function
00937. 00000 - "not a single-group group function"*
*Cause:   
Action:
Thanks inadvace
Regards,
prasanna

It is not clear what you want. Code below will return a customer with highest total amout sold regardless of year:
select  calendar_year,
        cust_first_name,
        total_amount_sold max_amount_sold
  from  (
         select  calendar_year,
                 cust_first_name,
                 sum(amount_sold) total_amount_sold,
                 row_number() over(order by sum(amount_sold) desc) rn
           from  sales,
                 times,
                 customers
           where sales.cust_id=customers.cust_id
             and times.time_id=sales.time_id
           group by calendar_year,
                 cust_first_name
  where rn = 1
/Keep in mind, if more than one customer has that highest total amount sold and you want all such customers:
select  calendar_year,
        cust_first_name,
        total_amount_sold max_amount_sold
  from  (
         select  calendar_year,
                 cust_first_name,
                 sum(amount_sold) total_amount_sold,
                 rank() over(order by sum(amount_sold) desc) rn
           from  sales,
                 times,
                 customers
           where sales.cust_id=customers.cust_id
             and times.time_id=sales.time_id
           group by calendar_year,
                 cust_first_name
  where rn = 1
/And if you want top customer for each calendar year:
select  calendar_year,
        cust_first_name,
        total_amount_sold max_amount_sold
  from  (
         select  calendar_year,
                 cust_first_name,
                 sum(amount_sold) total_amount_sold,
                 row_number() over(partition by calendar_year order by sum(amount_sold) desc) rn
           from  sales,
                 times,
                 customers
           where sales.cust_id=customers.cust_id
             and times.time_id=sales.time_id
           group by calendar_year,
                 cust_first_name
  where rn = 1
/Keep in mind, if more than one have that highest total amount sold and you want all such customers:
select  calendar_year,
        cust_first_name,
        total_amount_sold max_amount_sold
  from  (
         select  calendar_year,
                 cust_first_name,
                 sum(amount_sold) total_amount_sold,
                 rank() over(partition by calendar_year order by sum(amount_sold) desc) rn
           from  sales,
                 times,
                 customers
           where sales.cust_id=customers.cust_id
             and times.time_id=sales.time_id
           group by calendar_year,
                 cust_first_name
  where rn = 1
/SY.
Edited by: Solomon Yakobson on Dec 22, 2011 9:24 AM

Similar Messages

  • Need objective sql and pl/sql question for preparing interview

    Hey buddy please help me, now I am preparing interview of sql and pl/sql where asking objective question, so I need online site for preparing interview, your suggestion would be greatly appreciated.

    Have you tried searching using one of the many Internet search engines?
    I expect that there are many kinds of sites out there that may cater to you.
    The only other recommendation I would have would be to review the documentation at http://tahiti.oracle.com. Probably the SQL Language Reference, PL/SQL Reference, Application Developer's Guide, and Concept's Guide.

  • SQL question - how to get only the leafs

    i have a table of departments
    create table departments (
      dept   number ,
      father number
    )this is the data
    1
    1/2
    1/2/4
    1/2/4/6
    1/2/4/7
    1/2/4/8
    1/3
    1/3/5
    1/3/9given a department number i need only the leafs (the lowest member in the hierarchy).
    for dept 2 i need 6, 7, 8
    for dept 3 i need 5 , 9
    for dept 5 i need 5
    this is my query
    select dept
    from departments
    where connect_by_isleaf = 1
    start with father = :X
    connect by prior dept = father;this query will work only if :X is not a leaf. for 2 and 3 this query will work but for 5 it will return nothing (since connect_by_isleaf is 0 if the department apears in the start with clause).
    thanks !

    try
    select dept
    from departments
    where connect_by_isleaf = 1
    start with dept = :X
    connect by prior dept = father;Dang very late
    Message was edited by:
    Versatile

  • SQL - PL/SQL question for you SQL degenerates.

    I wish to create a view from a tableZ as follows. I have a table with 4 columns. I want to group col1,col2 and col3 based upon the value of col4. The value of col4 is based on a algorithm that needs to search for the lowest number in that particular grouping. So, from the example I am listing the value of col4 in the first block (A,A,A) is 1 since the smallest number in that block of 4 rows is a 1. Second block value would be=4 (A,A,B) since there are all 4's in the last column. Third Block (AAC) would be = 2 since we have 2,2,3,3. Fourth block (AAD) would be = 3 since we have 3,3,3,4 and the Fifth block (AAE) would be a 1 since we have 1,1,1,1. Remember the value is equal to the lowest integer of the four. The integer 1 is the lowest value in any list so if you loop and search the list and find a value of 1 you can exit at that point and automatically assign a one. So the Summary view would look like this based upon the sample values in the tableZ contents.
    A A A 1
    A A B 4
    A A C 2
    A A D 3
    A A E 1
    Table Z Contents of
    col1,col2,col3,col4
    ========================
    A A A 1
    A A A 1
    A A A 2
    A A A 3
    A A B 4
    A A B 4
    A A B 4
    A A B 4
    A A C 2
    A A C 2
    A A C 3
    A A C 3
    A A D 3
    A A D 3
    A A D 3
    A A D 4
    A A E 1
    A A E 1
    A A E 1
    A A E 1
    Thanks in advance,
    Anon

    I am using a fairly common slang use of the word in Information Technology offices throughout the United States[Humpty Dumpty language|http://www.wordspy.com/words/HumptyDumptylanguage.asp]
    n. An idiosyncratic or eccentric use of language in which the meaning of particular words is determined by the speaker.
    As in
    "There's glory for you!"
    "I don't know what you mean by 'glory,' " Alice said.
    Humpty Dumpty smiled contemptuously. "Of course you don't—till I tell you. I meant 'there's a nice knock-down argument for you!' "
    "But 'glory' doesn't mean 'a nice knock-down argument,' " Alice objected.
    "When I use a word," Humpty Dumpty said, in rather a scornful tone, "it means just what I choose it to mean—neither more nor less."
    Lewis Carroll, Alice through the Looking Glass
    Cheers, APC
    blog: http://radiofreetooting.blogspot.com

  • How to add a custom PL/SQL code for a button event handler

    Hi All,
    I am a toddler in using Oracle Portal. So please forgive me for my ignorance.
    Q : How do I add a custom PL/SQL code for a button event handler?
    Basically, I would like to write MY PL/SQL function and call it. I could see that we can write "CUSTOM" code as "PL/SQL button event handler" in the form design window. But the question is that it expects only a "call" to procedure. But where do I define the procedure then? If I insert the procedure from the backend, it gets flushed the next time I compile my form.
    Hope I am able to explain my point.
    Thanks in advance,
    Abbas.

    Hi All,
    I am a toddler in using Oracle Portal. So please forgive me for my ignorance.
    Q : How do I add a custom PL/SQL code for a button event handler?
    Basically, I would like to write MY PL/SQL function and call it. I could see that we can write "CUSTOM" code as "PL/SQL button event handler" in the form design window. But the question is that it expects only a "call" to procedure. But where do I define the procedure then? If I insert the procedure from the backend, it gets flushed the next time I compile my form.
    Hope I am able to explain my point.
    Thanks in advance,
    Abbas.

  • Handling DST in SQL Query for UCCX Custom Report

    We wrote all custom reports for one of the call centers using our UCCX deployment.  One problem we see we will hit in the future is DST.  We suggested they use UTC but they wanted to see the call data based off of EST timezone.  Right now we are okay because we use -5 to get the correct data but come March we are wondering how to address the issue.  What options do we have?  How are other people handling DST with the SQL queries for custom reporting?  I see that the HR client will determine this based off of the local computer time then gives you the option to use UTC.  We have all of our queries in an Excel document that the customer just needs to open and select Refresh All to update their data.
    Thanks

    "case-when" statements are evaluated in order.
    so you must do something like this:
    SELECT
    CASE WHEN <is not number>THEN 'N'
    CASE WHEN <is greater than 0>THEN 'Y'
    Now "<is greater than 0>" will always have number for input, can't get "not number" error there.
    See this thread:
    Re: regular expression: integer is between N..M
    Edited by: CharlesRoos on May 27, 2010 5:03 AM

  • TOP questions for Eseries devices - not so new!

    Just noticed that the thread titled:
    TOP questions for Eseries devices - start here [new]
    Really isn't so new dated 30-Cot-2007 11:48 AM - last edited on 30-Oct-2007 11:48 AM
    The post suggests that the first thing to do is update to the latest version of software.
    Alas the last update for E72 was 27 October 2010 which is flawed!  I know as my phone has misbehaved since installing it and I see other users reporting similar if not the same issues here.
    *#0000# reports version 052.005.217.11
    Question - How does one down grade to previous version?
    The post then suggests "If you still experience problems, you can try if formatting your Eseries device helps. Format the device by dialling *#7370#. The device will request a security code, the default code is 12345 unless you have changed it."
    Well actually on the E72 this does nothing!  I Type in *#7370# and its displayed to me and nothing else happens.  If I enter *#0000# I get the version number so it seems the software/firmware does not understand the code above!
    I did try 'factory settings' option from one of the control panel menu's instead at some point of my misery but was surprised by just how little effect that had - many things were not reset.
    If your still reading, I thought I would share some steps I have found to sometimes help on E72 when it appears to hang / stall:
    1. Try holding down the home button and if the running applications bar is shown try closing the applications by pressing the delete (backspace) key.
    2.- If that fails try pressing the off button and selecting 'offline' mode - This sometimes works - if it does then try previous point before going back to an online mode such as 'general'.
    3. If that fails - try holding down the power button to turn device off - that sometimes works! But sometimes the keyboard lights simply stay on until the battery goes dead...
    4. Remove the battery wait a moment and then re-insert battery.  You may then have to enter the time and date. Do check your alarms - during GMT I noticed all my alarms would have incremented by an hour!  Not seen this since BST started.

    Very strange - or perhaps not that strange but just another issue....  I tried the Hard Reset code again at this time it worked!!!  I'm now re-entering my details and remembering what I didn't back up   But if it fixes my issues it will be worth it.
    FYI from another fine post I found:
    FOR SOFT-RESET:
    - at Standby Screen type-in => *#7780#
    It will ask for “Restore all phone settings-phone’ll restart….”
    Then it asks for security code enter factory default => 12345
    FOR HARD-RESET:
    - at Standby Screen type-in => *#7370#
    It will ask for “Restore all phone settings-phone’ll restart….”
    Then it asks for security code enter factory default => 12345
    FOR FLASHING- TOTAL RESTORE: (Do this if your phone does not boot up)
    1) Remove the battery, and then wait for about 20 min or so before putting it back
    2) Press and hold these three keys together -Green dial key, Star key[*], Three key [3]
    3) switch ON the phone.
    4) Do not let go the three keys until you see the WELCOME screen displayed and just let it complete the boot process
    if this doesnt help contact Nokia Care Point-> http://europe.nokia.com/A4388379

  • How can I change my security questions for my Apple ID. I can't seem to get the questions correct at the moment

    How can I change my security questions for my Apple ID. I can't seem to get the questions correct at the moment

    The Best Alternatives for Security Questions and Rescue Mail
        a. Send Apple an email request at: Apple - Support - iTunes Store - Contact Us.
        b. Call Apple Support in your country: Customer Service: Contact Apple support.
        c. Rescue email address and how to reset Apple ID security questions.

  • SQL Query for TOP 10 Average CPU

    Have a SCOM Report request for a line graph showing top 10 average CPU for a group of servers. I have a query that will show all of the servers in a group for the last day, with the average CPU by hour. How can I extend the SQL query to only select the TOP
    10 average CPU from the group? Here is the Query I have:
    SELECT
    vPerf.DateTime,
    vPerf.SampleCount,
    cast(vPerf.AverageValue as numeric(10,2)) as AverageCPU,
    vPerformanceRuleInstance.InstanceName,
    vManagedEntity.Path,
    vPerformanceRule.ObjectName,
     vPerformanceRule.CounterName
    FROM Perf.vPerfHourly AS vPerf INNER JOIN
     vPerformanceRuleInstance ON vPerformanceRuleInstance.PerformanceRuleInstanceRowId = vPerf.PerformanceRuleInstanceRowId INNER JOIN
     vManagedEntity ON vPerf.ManagedEntityRowId = vManagedEntity.ManagedEntityRowId INNER JOIN
     vPerformanceRule ON vPerformanceRuleInstance.RuleRowId = vPerformanceRule.RuleRowId
    WHERE
    vPerf.DateTime  >= DATEADD(Day, -1, GetDate())
    AND vPerformanceRule.ObjectName like '%Processor Information%'
    AND vPerformanceRuleInstance.InstanceName = '_Total'
    AND (vPerformanceRule.CounterName IN ('% Processor Time'))
    AND (vManagedEntity.Path IN (SELECT dbo.vManagedEntity.Name
    FROM dbo.vManagedEntity INNER JOIN
    dbo.vRelationship On dbo.vManagedEntity.ManagedEntityRowId = dbo.vRelationship.TargetManagedEntityRowId INNER JOIN
    dbo.vManagedEntity As CompGroup On dbo.vRelationship.SourcemanagedEntityRowId = CompGroup.ManagedEntityRowId
    WHERE CompGroup.DisplayName = 'bemis ibb prod'
    ORDER BY path, vPerf.DateTime
    Results
    DateTime
    SampleCount
    AverageCPU
    InstanceName
    Path
    ObjectName
    CounterName
    2/26/15 3:00 PM
    2
    1.98
    _Total
    servername.corp.com
    Processor Information
    % Processor Time
    2/26/15 4:00 PM
    2
    2.09
    _Total
    servername.corp.com
    Processor Information
    % Processor Time
    2/26/15 5:00 PM
    2
    1.72
    _Total
    servername.corp.com
    Processor Information
    % Processor Time
    2/26/15 6:00 PM
    2
    1.83
    _Total
    servername.corp.com
    Processor Information
    % Processor Time
    Thanks in Advance!
    Mike Hanlon

    Hi 
    Sql Query
    SELECT TOP 10
    vPerf.DateTime,
    vPerf.SampleCount, 
    cast(vPerf.AverageValue as numeric(10,2)) as AverageCPU,
    vPerformanceRuleInstance.InstanceName, 
    vManagedEntity.Path, 
    vPerformanceRule.ObjectName, 
     vPerformanceRule.CounterName
    FROM Perf.vPerfHourly AS vPerf INNER JOIN
     vPerformanceRuleInstance ON vPerformanceRuleInstance.PerformanceRuleInstanceRowId = vPerf.PerformanceRuleInstanceRowId
    INNER JOIN
     vManagedEntity ON vPerf.ManagedEntityRowId = vManagedEntity.ManagedEntityRowId INNER JOIN
     vPerformanceRule ON vPerformanceRuleInstance.RuleRowId = vPerformanceRule.RuleRowId 
    WHERE 
    vPerf.DateTime  >= DATEADD(Day, -1, GetDate())
    AND vPerformanceRule.ObjectName like '%Processor Information%'
    AND vPerformanceRuleInstance.InstanceName = '_Total'
    AND (vPerformanceRule.CounterName IN ('% Processor Time'))
    AND (vManagedEntity.Path IN (SELECT dbo.vManagedEntity.Name
    FROM dbo.vManagedEntity INNER JOIN
    dbo.vRelationship On dbo.vManagedEntity.ManagedEntityRowId = dbo.vRelationship.TargetManagedEntityRowId INNER
    JOIN
    dbo.vManagedEntity As CompGroup On dbo.vRelationship.SourcemanagedEntityRowId = CompGroup.ManagedEntityRowId
    WHERE CompGroup.DisplayName = 'bemis ibb prod'
    ORDER BY path, vPerf.DateTime
    Regards
    sridhar v

  • I'm getting this message " We are unable to validate this serial number for Lightroom . Please contact Customer Support " when installing on my Mac

    I'm getting this message " We are unable to validate this serial number for Lightroom . Please contact Customer Support " when installing on my Mac

    contact adobe support by clicking this link and then clicking 'still need help' as soon as it appears, https://helpx.adobe.com/contact.html

  • My i-phone Not charging because Sunken pins and Green Belt3 Power Mac Center said even my warranty still open until 30 October they cannot do nothing and refer me to a Toll Free Apple customer Service number..my question for what are thwy there?

    My i-phone 5s is not charging because of Sunken pins where the socket is plugged. According Power Mac Center at Green Belt3 even my warranty still open until 30 October they cannot do nothing and refer me to a Toll Free Apple customer Service number in Singapore!!! ..my question for what are they there? not alt all very friendly and helpful!!

    Send an e-mail with all this in it directly to Tim Cook. Seriously. You can send e-mail to him.
    You might also try this forum here for more ideas: http://forums.macrumors.com/index.php?

  • Got a question for all you peeps dos anyone know about i phones i have a i phone 3gs which i got unlocked i did a master reset or summin and just had a pic of apple so i plugged it in i tunes downloaded and it now says no service at the top of phone and i

    got a question for all you peeps
    dos anyone know about i phones i have a i phone 3gs which i got unlocked i did a master reset or summin and just had a pic of apple so i plugged it in i tunes downloaded and it now says no service at the top of phone and i tunes says invalid sim i put the correct sim in it used to be locked too and still says same pls any one with ideas?

    hi sorry what happoned is that ages ago i brought a i phone 3gs on 02 network i went to a sml phone shop and payed for them to unlock it. it has been fine till yesterday when i went to reset it from the phone it then turned off and came back on just just an image of a apple for about an hour so i connected to i tunes and it said downloading software after another hr it had finished but then i tunes said in had to insert a sim so i had to un plug the phone from laptop while i did this i put my orange sim in and the i phone said where do i live and had to connect to a internet connection but all the time saying no service where the signal bar is and then says activating i phone it took a few min and said couldnt finish it bec of the signal and to connect it to i tunes to do it so i connected it to itunes and i tunes just keeps saying invalid sim so i took my orange sim out and put a 02 sim in and is still saying invalid sim on itunes?

  • When trying to download apps on my new iPad I keep getting prompted to update my security questions for my safety. When I choose this option it freezes and won't load the questions, however, when I hit not now it won't let me download. What do I do?

    When trying to download apps on my new iPad I keep getting prompted to update my security questions for my safety. When I choose this option it freezes and won't load the questions, however, when I hit not now it won't let me download. What do I do?

    Reboot your iPad and then see if you can set the security questions.
    Reboot the iPad by holding down on the sleep and home buttons at the same time for about 10-15 seconds until the Apple Logo appears - ignore the red slider - let go of the buttons.

  • Oracle SQL query for getting specific special characters from a table

    Hi all,
    This is my table
    Table Name- Table1
    S.no    Name
    1          aaaaaaaa
    2          a1234sgjghb
    3          a@3$%jkhkjn
    4          abcd-dfghjik
    5          bbvxzckvbzxcv&^%#
    6          ashgweqfg/gfjwgefj////
    7          sdsaf$([]:'
    8          <-fdsjgbdfsg
    9           dfgfdgfd"uodf
    10         aaaa  bbbbz#$
    11         cccc dddd-/mnm
    The output has to be
    S.no    Name
    3          a@3$%jkhkjn
    5          bbvxzckvbzxcv&^%#
    7          sdsaf$([]:'
    8          <-fdsjgbdfsg
    10         aaaa  bbbbz#$
    It has to return "Name" column which is having special characters,whereas some special chars like -, / ," and space are acceptable.
    The Oracle query has to print columns having special characters excluding -,/," and space
    Can anyone help me to get a SQL query for the above.
    Thanks in advance.

    You can achieve it in multiple ways. Here are few.
    SQL> with t
      2  as
      3  (
      4  select 1 id, 'aaaaaaaa' name from dual union all
      5  select 2 id, 'a1234sgjghb' name from dual union all
      6  select 3 id, 'a@3$%jkhkjn' name from dual union all
      7  select 4 id, 'abcd-dfghjik' name from dual union all
      8  select 5 id, 'bbvxzckvbzxcv&^%#' name from dual union all
      9  select 6 id, 'ashgweqfg/gfjwgefj////' name from dual union all
    10  select 7 id, 'sdsaf$([]:''' name from dual union all
    11  select 8 id, '<-fdsjgbdfsg' name from dual union all
    12  select 9 id, 'dfgfdgfd"uodf' name from dual union all
    13  select 10 id, 'aaaa  bbbbz#$' name from dual union all
    14  select 11 id, 'cccc dddd-/mnm' name from dual
    15  )
    16  select *
    17    from t
    18   where regexp_like(translate(name,'a-/" ','a'), '[^[:alnum:]]');
            ID NAME
             3 a@3$%jkhkjn
             5 bbvxzckvbzxcv&^%#
             7 sdsaf$([]:'
             8 <-fdsjgbdfsg
            10 aaaa  bbbbz#$
    SQL> with t
      2  as
      3  (
      4  select 1 id, 'aaaaaaaa' name from dual union all
      5  select 2 id, 'a1234sgjghb' name from dual union all
      6  select 3 id, 'a@3$%jkhkjn' name from dual union all
      7  select 4 id, 'abcd-dfghjik' name from dual union all
      8  select 5 id, 'bbvxzckvbzxcv&^%#' name from dual union all
      9  select 6 id, 'ashgweqfg/gfjwgefj////' name from dual union all
    10  select 7 id, 'sdsaf$([]:''' name from dual union all
    11  select 8 id, '<-fdsjgbdfsg' name from dual union all
    12  select 9 id, 'dfgfdgfd"uodf' name from dual union all
    13  select 10 id, 'aaaa  bbbbz#$' name from dual union all
    14  select 11 id, 'cccc dddd-/mnm' name from dual
    15  )
    16  select *
    17    from t
    18   where translate
    19         (
    20            lower(translate(name,'a-/" ','a'))
    21          , '.0123456789abcdefghijklmnopqrstuvwxyz'
    22          , '.'
    23         ) is not null;
            ID NAME
             3 a@3$%jkhkjn
             5 bbvxzckvbzxcv&^%#
             7 sdsaf$([]:'
             8 <-fdsjgbdfsg
            10 aaaa  bbbbz#$
    SQL>

  • FM for getting Classification against Customer and Material

    hi friends..
    Is there any FM for getting Classification against Customer and Material.
    transaction VCH3. (strategy SD03)
    regards

    please help
    related tables are CABN and AUSP
    and transaction is VCH3 and strategy SD01

Maybe you are looking for

  • Online games from LAN cannont connect to Servers

    good day, i am Ryan, i am having problem with my Local Area Network. in my network i have 15 computer units. i have WRT54G2v1.0.04 linksys router to share internet connection. online games cannot connect to its respective game servers when there are

  • Two Internal Tables for ALV Grid

    Hi Gurus, I have a little problem here. I have a report to display cost of production. The rows is about 50 displaying amount in dollars (currency fields). I have this in ALV Grid. But my problem is that the last 4 lines of the report are not currenc

  • Must command link parameter variable SESSION Scope??

    I add a EJB Session Bean Method to my page which returns an array: public Province[] getProvinces(); When you place the Session Bean to the page, it automatically creates a REQUEST SCOPE VARIABLE called "provinceRemoteGetProvincesResultBean" in the t

  • Keyboard doesn't appear on conctacts

    Hi I get the following. my keyboard does not appear when I try to create or edit contacts, but can compose and send emails. someone with the same problem? thanks & regards Ps: I have ios7

  • Changed from Mac to Windows, serial number won't work.

    I have been using CS4 on my Mac for a couple of years but just got a new Toshiba laptop and using Windows now. I have downloaded CS4 but serial number is not working, I assume because the serial number is for mac. Is this right? Can I get a new seria