Stupid old backpacker (me) cannot understand why this query returns 1 row

Hi all

In reference to {: identifier of the thread = 2456973}, why do
select sum(count(decode(job, 'CLERK', 1, null))) CLERKS
, sum(count(decode(job, 'SALESMAN', 1, null))) SALESMANS
from emp group by job;
only 1 rank and not 1 for each task? In fact, I had to test it myself to believe.

It returns the data as if the query were
select sum(CLERKS), sum(SALESMANS)
from (select count(decode(job, 'CLERK', 1, null)) CLERKS, count(decode(job, 'SALESMAN', 1, null)) SALESMANS
         from emp group by job)
Using only a single aggregate (count or sum) returns 1 row per job, as expected

John Stegeman wrote:
It returns the data as if the query were

select sum(CLERKS), sum(SALESMANS)
from (select count(decode(job, 'CLERK', 1, null)) CLERKS, count(decode(job, 'SALESMAN', 1, null)) SALESMANS
from emp group by job)

Exactly the point ;-)

It seems that Oracle actually do, a group of 'double' in the same operation.
Attend plans to explain in this example:

SQL> select count(decode(job, 'CLERK', 1, null)) CLERKS
  2       , count(decode(job, 'SALESMAN', 1, null)) SALESMANS
  3  from scott.emp group by job;

    CLERKS  SALESMANS
---------- ----------
         0          0
         0          0
         0          0
         0          4
         4          0

Execution Plan
----------------------------------------------------------
Plan hash value: 1697595674

---------------------------------------------------------------------------
| Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |      |     5 |    40 |     4  (25)| 00:00:01 |
|   1 |  HASH GROUP BY     |      |     5 |    40 |     4  (25)| 00:00:01 |
|   2 |   TABLE ACCESS FULL| EMP  |    14 |   112 |     3   (0)| 00:00:01 |
---------------------------------------------------------------------------

And compare it to the one with the double aggregates:

SQL> select sum(count(decode(job, 'CLERK', 1, null))) CLERKS
  2       , sum(count(decode(job, 'SALESMAN', 1, null))) SALESMANS
  3  from scott.emp group by job;

    CLERKS  SALESMANS
---------- ----------
         4          4

Execution Plan
----------------------------------------------------------
Plan hash value: 417468012

----------------------------------------------------------------------------
| Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------
|   0 | SELECT STATEMENT    |      |     1 |     8 |     4  (25)| 00:00:01 |
|   1 |  SORT AGGREGATE     |      |     1 |     8 |     4  (25)| 00:00:01 |
|   2 |   HASH GROUP BY     |      |     1 |     8 |     4  (25)| 00:00:01 |
|   3 |    TABLE ACCESS FULL| EMP  |    14 |   112 |     3   (0)| 00:00:01 |
----------------------------------------------------------------------------

There are GROUP BY hash and SORT GLOBAL times.

It is really unnecessary to an aggregate on an aggregate - if two aggregates are used "in the same group level.
Sum() aggregates are used on an already aggregated value, so it doesn't look like Oracle which actually cures like 'first do the internal aggregate using the group specified by and then do the external aggregation on the result with any group.'

Look at this example where I combine aggregates "double" with "single" aggregates:

SQL> select sum(count(decode(job, 'CLERK', 1, null))) CLERKS
  2       , sum(count(decode(job, 'SALESMAN', 1, null))) SALESMANS
  3       , count(decode(job, 'SALESMAN', 1, null)) SALESMANS2
  4       , count(*) COUNTS
  5  from scott.emp group by job;

    CLERKS  SALESMANS SALESMANS2     COUNTS
---------- ---------- ---------- ----------
         4          4          1          5

Execution Plan
----------------------------------------------------------
Plan hash value: 417468012

----------------------------------------------------------------------------
| Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------
|   0 | SELECT STATEMENT    |      |     1 |     8 |     4  (25)| 00:00:01 |
|   1 |  SORT AGGREGATE     |      |     1 |     8 |     4  (25)| 00:00:01 |
|   2 |   HASH GROUP BY     |      |     1 |     8 |     4  (25)| 00:00:01 |
|   3 |    TABLE ACCESS FULL| EMP  |    14 |   112 |     3   (0)| 00:00:01 |
----------------------------------------------------------------------------

When you mix "doubles" and "single" aggregates, Oracle decides that unique aggregates belong to the 'outer' aggregation
SALESMAN2 did a count on the aggregated work column which is the result of the 'internal' group by - so only 1.
The count (*) is also the result of the aggregation of the 'internal '.

I don't know if it's documented or if it is an 'effect' of internal code used for GROUPING SETS or the internal code used to enable the analytical functions like this:

SQL> select count(decode(job, 'CLERK', 1, null)) CLERKS
  2       , count(decode(job, 'SALESMAN', 1, null)) SALESMANS
  3       , sum(count(decode(job, 'CLERK', 1, null))) over () CLERKS2
  4       , sum(count(decode(job, 'SALESMAN', 1, null))) over () SALESMANS2
  5  from scott.emp group by job;

    CLERKS  SALESMANS    CLERKS2 SALESMANS2
---------- ---------- ---------- ----------
         0          0          4          4
         4          0          4          4
         0          0          4          4
         0          0          4          4
         0          4          4          4

Execution Plan
----------------------------------------------------------
Plan hash value: 4115955660

----------------------------------------------------------------------------
| Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------
|   0 | SELECT STATEMENT    |      |     5 |    40 |     4  (25)| 00:00:01 |
|   1 |  WINDOW BUFFER      |      |     5 |    40 |     4  (25)| 00:00:01 |
|   2 |   SORT GROUP BY     |      |     5 |    40 |     4  (25)| 00:00:01 |
|   3 |    TABLE ACCESS FULL| EMP  |    14 |   112 |     3   (0)| 00:00:01 |
----------------------------------------------------------------------------

Personally, I think that I would have preferred if Oracle has raised an error on this "double aggregation" and therefore require me to write this way (if it's the result I wanted):

select sum(CLERKS), sum(SALESMANS)
from (select count(decode(job, 'CLERK', 1, null)) CLERKS, count(decode(job, 'SALESMAN', 1, null)) SALESMANS
         from emp group by job)

I don't really see a good use case for aggregations of 'double'-, but rather that he could give you undetected bugs in your code, if you happen to do double aggregation without noticing.

Interesting thing to know ;-)

Tags: Database

Similar Questions

  • Can't understand why this query returns multiple lines with the same data

    Hi all
    I am a relative novice and self-taught when it comes to SQL. I wrote a query to our reporting tool that returns multiple rows, and I can't understand why. I know that I can use the SELECT DISTINCT option, but it really slows the execution when I do. I'd really rather understand if I can change the code to avoid the multiples. This is the query. I've included a few statements in italics to help explain the break. Any ideas?

    SELECT MATSITE, MATPONUM, FIRSTRECPTDATE
    Of
    Subquery that concludes the first date on which purchase orders have been implemented with ACK State
    (SELECT ACKSTAT. PONUM AS 'ACKPONUM', (MIN (ACKSTAT. CHANGEDATE)) AS 'FIRSTACKDATE '.
    OF PZMAX. POSTATUS ACKSTAT
    WHERE (ACKSTAT. STATE = 'ACK') AND (ACKSTAT.ORGID ='CGSALTUS)
    GROUP OF ACKSTAT. PONUM),
    Subquery that concludes the first reception against a purchase order transaction for purposes of comparison
    (SELECT TRANS. PONUM AS "MATPONUM", TRANS. SITEID AS 'MATSITE', (MIN (TRANS. TRANSDATE)) AS 'FIRSTRECPTDATE '.
    OF PZMAX. MATRECTRANS TRANS
    WHERE (TRANS.ORGID ='CGSALTUS) AND (TRANS. HOUR > =: startDate and TRANS. TRANSDATE < =: endDate)
    TRANS GROUP. SITEID, TRANS. PONUM)
    WHERE
    (ACKPONUM = MATPONUM AND FIRSTRECPTDATE < FIRSTACKDATE) OR (NOT EXISTS (SELECT 1 FROM PZMAX. POSTATUS ACKSTAT2 WHERE (ACKSTAT2. PONUM = MATPONUM) AND (ACKSTAT2. STATE = 'ACK') AND (ACKSTAT2.ORGID ='CGSALTUS)))

    The where the instruction is intended to find when one of two conditions exists. ((1) received happened before the command either in ACK or 2) a reception that's happened, but the purchase order is never in ACK State. It seems that this second condition that creates multiple lines.

    Any thoughts will be appreciated geratly.

    Dave Teece
  • Why this query produces no output?

    Why this query produces no output?
    select * from
    (
    SELECT 40 as startvalue, (24 * 60)*(To_Date('00:40', 'HH24:MI') - To_Date('00:00', 'HH24:MI')) as c
    FROM dual di
    ) q
    where q.c = q.startvalue

    And just to show that it works if round you...

    SQL> ed
    Wrote file afiedt.buf
    
      1  select * from
      2  (
      3  SELECT 40 as startvalue, round((24 * 60)*(To_Date('00:40', 'HH24:MI') - To_Date('00:00', 'HH24:MI')),0) as c
      4  FROM dual di
      5  ) q
      6* where q.c = q.startvalue
    SQL> /
    
    STARTVALUE          C
    ---------- ----------
            40         40
    

    I certainly wouldn't say using TRIM as PS has suggested. TRIM is a string function, not a digital function.

  • Why this query can remove duplicates?

    Why this query can remove duplicates? Can someone give me detailed explanation?

    Thank you
    select salary from employees union select salary from employees;

    Hello

    See the docs.

    ' Example of the UNION
    The following statement combines the results of two queries with the UNION operator which eliminates duplicates of selected lines.
    "This statement shows that you must match the data type (using the function TO_CHAR) when the columns do not exist in one or the other table"

    http://download.Oracle.com/docs/CD/B19306_01/server.102/b14200/queries004.htm#i2054381

    Edit

    Here's another interpretation of your question:

    http://asktom.Oracle.com/pls/asktom/f?p=100:11:0:P11_QUESTION_ID:1224636375004

    Published by: hoek on October 22, 2009 17:40

  • TypeError: Error #1009: cannot understand why I make it

    Hi, I keep getting the error above, Error #1009: cannot access a property or method of a null object reference. and can't understand why I'm getting it.

    I get it in the last line of the following function:

    public function frameEvents (): void

    {

    _playerClass.update ();

    _playerClass.render ();

    _playerClass.updatePlayerShot ();

    _scroll.update ();

    _collision.playerVsGround (_playerClass, foreground1);

    _collision.checkBullets (_playerClass.playerShot.playerShot.bitmap);

    _bigTurretOne.update (_playerClass.xPos, _playerClass.yPos, _scroll.scroll_Vx, _scroll.scroll_Vy, _bigTurretOne.x, _bigTurretOne.y);

    _bigTurretOne.x += _scroll.scroll_Vx;

    _bigTurretOne.y += _scroll.scroll_Vy;

    _bigTurretOne.render ();

    _bigTurrShot.moveMissiles ();

    _collision.checkMissiles (_bigTurrShot._missile.bitmap);

    }

    When I trace (_bigTurrShot._missile.bitmap) I get [object bitmap] so it is not upward with the null value when it's mapped. Everything seems to be OK in the other code I have for it, anyone have any idea why I get the errror?

    It is reactionary and not very elegant but check if the object is not null before accessing its property. If _collision.checkMissiles(_bigTurrShot._missile.bitmap); is giving the null object error, try

    if(_bigTurrShot._missile != null) _collision.checkMissiles(_bigTurrShot._missile.bitmap);
    

    (You have not shown enough code for an "adequate" solution)

  • Do not understand why this partition by does not include a function of group

    It's the oradocs

    SELECT name, salary, department_id,

    PERCENTILE_CONT (0.5) INTRA GROUP (ORDER BY salary DESC)

    COURSES (PARTITION BY department_id) "Percentile_Cont."

    PERCENT_RANK()

    COURSES (PARTITION BY department_id ORDER BY salary DESC) "Percent_Rank.

    Employees

    WHERE department_id IN (30, 60)

    ORDER BY last_name, salary, department_id;

    http://docs.Oracle.com/database/121/SQLRF/functions140.htm#i1000909

    I recently moved from analytical functions - the PARTITION OF analytical functions I practised so far have prescribed a group by article.

    I don't understand why it does not include a.

    Any tips?

    There is no need to include a GROUP BY in your query, simply because you use analytical functions.

    The main point of the use of analytic functions is to allow you to perform the aggregation or other lines of reference data without having to group data in the normal sense.  The 'score' window, is what defines the data group that you want to reference without actually the outcome of consolidation.

  • No. phones service smart blackBerry, cannot understand why.

    My Blackberry Curve has currently no service, and can't firure why. For the record, I'm home, and I've always had the service before. So here's what I can tell:

    * Instead of saying 'connected to T-Mobile' liike it usually does, on the front screen, it says: "failed to initialize."

    * In the State of the Service, only the voice service says "emergency".

    * In the Mobile Network Options, there my mobile network such as AT & T, but my network is T-Mobile, and I didn't AT & t at any time just by owning the phone.

    Any help? The last time something like this happened was when I forgot to pay my phone bill, butI talked to T-Mobile, and is not the problem. Thanks in advance!

    OK, so it seems that I answered my own question. I was still with my old phone SIM card, and he died. So I took one that came with my curve and has been change to T-Mobile to that one, and now it's great to be working again. Thanks for all the suggestions!

  • Use of memory Windows 7 - excess and I cannot understand why

    I have a Windows 7 computer with gigabytes of RAM, which should be more than enough for a user like me. However, my computer has sometimes slows down, so I used the Task Manager. I discovered that too large amount of memory was used. This has steadily increased. Now, when I start my computer, my memory usage starts at 38% of the amount of space available and then increased to about 45% of the memory. The culprit is not a virus, as I did several malware analyses, nor is it a memory problem. Task Manager and performance monitor data just came over me, and I can't find the root of the problem. Can anyone suggest a solution or a way to understand the problem? Thank you!

    In order to diagnose your problem, we need run Windows performance toolkit, the instructions that are in this wiki

    If you have any questions do not hesitate to ask

    Please run the trace when you encounter the problem
  • Every e-mail I receive is delivered with a double. I tried to look at the various features of the program, but I can't understand why this is happening. Help!

    This happened for several years now. After the updates, I started having duplicates. I lived with the problem for a long time because I could still get the emails, if more abundantly. My volume of e-mail has gone upward and upward, however, and I now get 60 or 70 e-mails a day because of this problem. Can someone tell me how to solve this problem?

    The popstate file is re-created automatically when you restart TB and if the original has been altered, see if you no longer receive messages double. To find accounts, please post your info as described here:

    https://support.Mozilla.org/en-us/KB/ask-TB#w_how-to-ask-your-question

    You can omit the details of the printer and the police.

  • Hard drive shows almost full but cannot understand why

    Hello

    My C drive shows me using 565 GB with a total area of 596 GB so I'm close to running out of space.

    Strange thing is that I can't know which uses all the space!

    I looked at the size of all files on the C drive, and what follows is the biggest:

    Program x 86: 32 GB

    Windows: 50GB

    Users: 271GB

    Which makes a total of about 350 GB, this is far from the projection of 565 GB used when I look at the properties of the C drive.

    So, where's the rest?

    I have the list hidden files and I looked at disk cleanup and defragmentation.  I also deleted the files in system restore, but it's all the little things.

    The difference, I'm looking for is huge then where is he?

    Max

    Control Panel / System / Protection system allows you to choose the amount of disk space to use for the Restore Points. I use 5 GB that gives me about 6 points of restoration.

  • My computer freezes and gets the blue screen at least three times a day. I cannot understand why, and I'm frustrated. Help, please!

    My computer makes sure to plant three to five times a day. It always ends with the blue screen of death and strong buzz. I think it's perhaps because of Spotify, but I've updated, reloaded and all and yet the program itself and my computer still seems to hang. I really don't think that it is good for my computer hangs at 3 times a day. I've had this computer for about 2 months and it is brand new. (Windows 7, I use Google Chrome, it's an Acer 5250-639. I'm frustrated and would be really grateful for the help!

    That's a lot of dump files :)

    Bug WORKER_THREAD_RETURNED_AT_BAD_IRQL control has a value of 0x000000E1. This indicates that a thread of work completed and returned with IRQL > = DISPATCH_LEVEL.

    Had suddenly look and according to the atikmpag.sys whocrashed pilot next is the cause of the crash. It's your ATI graphics card driver. You must go to www.ati.com then goto support and drivers and download it from there.

    Although it suggests, it's the driver causing the problem it may not be the problem. However, it is a good place to start.

  • I can't understand why this hitTest doesn't work

    Hey,.

    Can you tell me why it does not work?

    To me, it seems perfect.

    And it is in the main timeline.

    onEnterFrame = function () {}


    for (i = 0; i! = 100; i ++) {}


    If (_root ["redx" + i] .hitTest (_root.yellow)) { }


    play();


    }

    }

    }

    Thanks for the help!

    Use the trace() function to see if you movieclip references are correct.

  • That means 1e9 and why this query does not work?

    What does 1e9? Someone has links to documentation on this oracle? And why I get this error?
    SQL> select segment_name,(bytes/1e9) AS size from dba_segments where segment_name='MSG_MASTER';
    select segment_name,(bytes/1e9) AS size from dba_segments where segment_name='MSG_MASTER'
                                       *
    ERROR at line 1:
    ORA-00923: FROM keyword not found where expected

    SIZE is a keyword - so if you want the name of the column size then use 'SIZE' else give it a different name

    Try dividing by other exponentials, then you'll see how: 1e0 1e1 (div 1), (div by 10), 1e2 :-) etc

    Mette

    Published by: mettemusens on 2009-05-12 16:02

  • Why this sql returns ORA-01427: einreihig subquery returns multiple rows.

    Select

    case when 'Y'=(select  emp_sw

    of the customer

    where cust_co_num =   :custconum   )

    then ( Select cust_id from )

    client where

    cust_co_num = :custconum 

    )

    on the other

    (select...)

    end while pays_id

    of the double

    or any other solution for this?

    Thank you!!

    Maybe

    with

    data in the form of

    (select cust_id 100, 'Y' emp_sw, 1 cust_co_num of all the double union)

    Select 200, "n", 1 Union double all the

    Select 300, 'Y', 3 double Union all

    Select 400, ', 2 double

    )

    Select cust_id, emp_sw, cust_co_num

    data d

    where cust_id = case when exists (select null

    from the data

    where cust_co_num =: custconum

    and emp_sw = 'Y '.

    )

    then cust_id

    end

    or cust_id in (select cust_id

    from the data

    where cust_co_num =: custconum

    and emp_sw = n

    )

    Concerning

    Etbin

  • Why this query SQLLite returns the same all the time?

    Hello

    I use a search box to accept a query on three columns and am page before based on the last record, which in this case is Run Baby Run by Loopy

    I know for a fact that the database has a song inside by Loopy called Straight Down the Line, so this should at least be showing that. But it does is display the same songs again.

    Can someone explain the error in my logic here?

    SELECT * WHERE DiscID AS "loopy %" songs or artist LIKE 'loopy %' or AS "loopy %" title AND artist > = 'LOOPY' COLLATE NOCASE Title > = 'Run Baby Run' COLLATE NOCASE ORDER BY artist COLLATE NOCASE ASC, title COLLATE NOCASE ASC LIMIT 20

    Thanks for taking a peek.

    This is a forum for AS3, not SQL - etc., which may explain the slow Pickup on your ad.  While someone might offer something at some point, you should try to find a forum where they discuss SQL programming, which could mean going out of the domain of Adobe.  The closest thing I can think that would be a forum in the Adobe forums game...

    http://forums.Adobe.com/community/Dreamweaver/server_side

Maybe you are looking for

  • How I sent empty the mailbox?

    I have 3,000 more messages in my sent mailbox.  With the help of El Capitan, how do I empty it?

  • Remove my name from emails

    I want to remove my name, which shows when someone opens an email me

  • [request] Signature of the App using RBR, CPR, RRT

    Hi all I want to create a new version of the app. The app is built using Webworks 1.0. But when I tried to sign, it always displays error because I'm not using the same key signature. How to find the old signature key? Could we ask the signing key us

  • Add SX20 in TMSPE

    Hi all TMS version is 1.4 TMSPE, SX20 is 7.2.1 and X8.2.2 VCS 14.6.2, I want to manage/configure a SX20 existing via the provision of TMS. The SX20 is already configured; recorded at the VCSC and is added to the MSDS. In the TMS, I created a new grou

  • sensor to recreate the image via the service account?

    Hello, I have the following problem with a JOINT-2 (4.1.5 S211) module: I am able to get to the screen to login via SSH. I connect with my login and my password but the following error: cannot communicate with authenticationApp (getUserAccountConfig)