Getting A Count In One SQL Statement

Since I don't know how to do what I'm about to ask, I would normally create a table (tbl1) with the main dataset I want and then create a second table (tbl2) with additional data I want, join the two and update tbl1 data with tbl2 data.
However, I would like to know how to do this in one SQL statement. I somehow need to link the count sql with the main body..?
So..I have to pull data by group id. Each group id can have a certain number of active members in it. I would like to use one SQL statement to pull the group id's and also, at the same time, give me a count of each group's active membership. Both the main and count statments in the below SQL include the emp_grps table which can obviously be linked so the right groups are updated..
Not sure how to begin to reflect this in an SQL statement, so I'll just give you the wrong version to show what data elements I have. The following gives the total count by all group's in each groups individual record. Of course, as mentioned, all I want is that group's share of the membership in their individual record:
select group_id,
(select count(*)
from elig elg
join emp_grps eg
on elg.group_id = eg.group_id
where eg.rmc_code in ('CR')
and elg.elig_start_date < sysdate
and elg.elig_end_date > sysdate) mbr_count
from odw.emp_grps eg
where eg.rmc_code in ('1M')
Output from this query:
GROUP_ID MBR_COUNT
A 10,000
B 10,000
C 10,000
D 10,000
What I want to see:
GROUP_ID MBR_COUNT
A 7,000
B 1,000
C 1,500
D 500
Thanks for any assistance..

Hi,
So you want one row for every distinct value of group_id, with a count that reflects just that group_id.
That sound like a job for GROUP BY group_id and the aggregate COUNT function, like this:
SELECT    eg.group_id
,       COUNT ( CASE
                  WHEN  eg.rmc_code  IN ('CR')
                THEN  1
              END
            )     AS mbr_count
FROM        elig           elg
JOIN       emp_grps      eg    ON   elg.group_id  = eg.group_id
WHERE       eg.rmc_code             IN ('CR', '1M')
AND       elg.elig_start_date < SYSDATE
AND       elg.elig_end_date   > SYSDATE
GROUP BY  eg.group_id
HAVING       COUNT ( CASE
                  WHEN  eg.rmc_code  IN ('1M')
                THEN  1
              END
            ) > 1
ORDER BY  eg.group_id
;It's unclear what you're trying to do with eg.rmc_code. I'm guessing you want to count the rows where it's one value ('CR'), but only display groups that also have another value ('1M').
Of course, I can't say for sure without seeing your actual tables, or at least small test versions of them.
Post CREATE TABLE and INSERT statements (relevant columns only) for all tables involved, and the resutls you want from that sample data (if it's not the results you already posted).
Always say which version of Oracle you're using.

Similar Messages

  • How can i use one SQL statement to solve problem?

    How can i use one SQL statement to solve the question below?
    For a Table named A, there is a column named F(char type).
    Now select all the records where F like '%00' and update their F value to '%01'
    Just one SQL statement.Do not use PL/SQL block.
    How to do that?
    Thanks.

    What is the data volume for this table?
    Do you expect lots of rows to have '%00' as their value?
    Following two statements come to mind. Other experts would be able to provide better alternatives:
    If you have index on SUBSTR(f, 2):
    UPDATE A
    SET    f = SUBSTR(f,
                      1,
                      length(f) - 2) || '01'
    WHERE  substr(f,
                  -2) = '00';If most of the rows have pattern '%00':
    UPDATE A
    SET    f = SUBSTR(f,
                      1,
                      length(f) - 2) ||
               DECODE(SUBSTR(f,
                             -2),
                      '00',
                      '01',
                      SUBSTR(f,
                             -2));

  • Can you really update two tables in one SQL statement

    Ok a post in the forum has got me awefully curious:
    Can you update two tables in one update statement i.e something like this
    update table a , b
    set b.<column> = something
    a.<column> = something
    Something to this effect.
    If you are curious to know what post I am talking about it is called "updating a single row"

    No. You can only update one table in one SQL statement.

  • Execute just that one SQL statement ....

    Would like to request to add running just that one sql statement in the statment worksheet which has your cursor in it without having to select the entire statement.
    Updating any part of a statement deselects it ..... reselecting a larger statement is cumbersome and time consuming
    Regards
    Ronald

    There are some problems with the statement selection (as per the other reply) but you can run just the current statement that the cursor is in, with the F9 or the Run Statement button on the SQL Worksheet.
    If you are used to using TOAD where blank lines are seperators, remember that Raptor expects you to terminate your SQL statements with a ; and your PL/SQL statements with a / (on a new line).

  • The best way to do paging and get total rows count given a sql statement

    Hi,
    Just got a quick question.... what is the best way to do paging as well as the total rows count given by a sql statement.
    e.g. "select * from emp"
    1. I need to know the total row count for this statement.
    2. I also need to do a 10 rows per page....
    Is there a way to do it in a SINGLE statement for best performance?
    Thanks experts.

    Sounds more like a "formatting" problem...
    If Sql*plus is your reporting tool, check out the guide:
    http://download-west.oracle.com/docs/cd/B10501_01/server.920/a90842/toc.htm

  • One SQL Statement executed abnormally in Oracle10g Database

    One programmer sent the following SQL to me, and ask why no result was returned. I knew that the SQL Statement was not good in writting and designing.
    So, first we don't focus on it. we only focus on why no result was returned.
    SELECT 'other Accts', 'Other Accts', TO_NUMBER(''),TO_DATE('2010-10-9', 'yyyy-MM-dd')
    FROM dual
    WHERE *0 = (SELECT COUNT(*)*
    FROM (SELECT 'other Accts', 'Other Accts',SUM(a.qty_invoiced), a.sell_week_date
    FROM sales_in_oracle_data a
    WHERE NOT EXISTS
    (SELECT pa.partner_number
    FROM partner pa
    WHERE pa.partner_number = a.customer_number)
    AND a.sell_week_date >=TO_DATE('2010-10-9', 'yyyy-MM-dd')
    AND a.sell_week_date <=TO_DATE('2011-1-1', 'yyyy-MM-dd')
    AND a.qty_invoiced >= 0
    AND EXISTS
    (SELECT pp.product_id
    FROM product_pn pp, product p
    WHERE pp.magellan_pn = a.material
    AND pp.product_id = p.product_id )
    GROUP BY a.sell_week_date
    the SQL sub Statement:
    SELECT COUNT(*)*
    FROM (SELECT 'other Accts', 'Other Accts',SUM(a.qty_invoiced), a.sell_week_date
    FROM sales_in_oracle_data a
    WHERE NOT EXISTS
    (SELECT pa.partner_number
    FROM partner pa
    WHERE pa.partner_number = a.customer_number)
    AND a.sell_week_date >=TO_DATE('2010-10-9', 'yyyy-MM-dd')
    AND a.sell_week_date <=TO_DATE('2011-1-1', 'yyyy-MM-dd')
    AND a.qty_invoiced >= 0
    AND EXISTS
    (SELECT pp.product_id
    FROM product_pn pp, product p
    WHERE pp.magellan_pn = a.material
    AND pp.product_id = p.product_id )
    GROUP BY a.sell_week_date
    it returned 0 truely. But the entire SQL didn't return any data.
    why can it execute like above description?  I guess that it maybe go against oracle basic rule.
    Any one give me some suggestion?
    Edited by: [email protected] on 2010/7/19 下午 6:09

    I managed to track down a 10.2.0.4 instance and can confirm that this statement does not return the correct results.
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    SQL> select *
      2  from   dual
      3  where  0 = (select count(*)
      4              from  (select dummy, sum(1)
      5                     from   dual
      6                     where  dummy = 'z'
      7                     group  by dummy
      8                    )
      9             );
    no rows selected
    SQL> explain plan for
      2  select *
      3  from   dual
      4  where  0 = (select count(*)
      5              from  (select dummy, sum(1)
      6                     from   dual
      7                     where  dummy = 'z'
      8                     group  by dummy
      9                    )
    10             );
    Explained.
    | Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |      |     1 |     2 |     4   (0)| 00:00:01 |
    |*  1 |  FILTER             |      |       |       |            |          |
    |   2 |   TABLE ACCESS FULL | DUAL |     1 |     2 |     2   (0)| 00:00:01 |
    |   3 |   SORT AGGREGATE    |      |     1 |     2 |            |          |
    |*  4 |    TABLE ACCESS FULL| DUAL |     1 |     2 |     2   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - filter( NOT EXISTS (SELECT /*+ */ 0 FROM "SYS"."DUAL" "DUAL"
                  WHERE "DUMMY"='z'))
       4 - filter("DUMMY"='z')
    Connected to:
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
    With the Partitioning, Real Application Clusters, OLAP, Data Mining
    and Real Application Testing options
    SQL> select *
      2  from   dual
      3  where  0 = (select count(*)
      4              from  (select dummy, sum(1)
      5                     from   dual
      6                     where  dummy = 'z'
      7                     group  by dummy
      8                    )
      9             );
    D
    X
    SQL> explain plan for
      2  select *
      3  from   dual
      4  where  0 = (select count(*)
      5              from  (select dummy, sum(1)
      6                     from   dual
      7                     where  dummy = 'z'
      8                     group  by dummy
      9                    )
    10             );
    Explained.
    | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |      |     1 |     2 |     6   (0)| 00:00:01 |
    |*  1 |  FILTER            |      |       |       |            |          |
    |   2 |   TABLE ACCESS FULL| DUAL |     1 |     2 |     3   (0)| 00:00:01 |
    |*  3 |   TABLE ACCESS FULL| DUAL |     1 |     2 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - filter( NOT EXISTS (SELECT 0 FROM "SYS"."DUAL" "DUAL" WHERE
                  "DUMMY"='z'))
       3 - filter("DUMMY"='z')
    17 rows selected.Notice that the explain plan is a bit different compared to the 11.2.0.1 release. My guess is that the optimizer is doing something weird.

  • One SQL Statement

    I have a text column with values like listed below:
    rec_num text_column
    10001 'Today_is__my_birthday.'
    10002 'I have__a___dog_and_a____cat.'
    where '_' indicates space.
    How can I use one SQL 'select ....' statement to get rid of the multiple spaces and replace with just one space?
    I expect a result like 'Today is my birthday.' or 'I have a dog and a cat.' with just one space between word.
    THANKS a million.

    Hi,
    SELECT     rec_num
    ,     REGEXP_REPLACE ( text_column
                     , ' +'          - or ' {2,}'
    FROM    table_x;As you've noticed, this site compresses white space by default.
    To post formatted text, type these 6 characters:
    &#123;code&#125;
    (small letters only, inside curly brackets) before and after sections of formatted text, to preserve spacing.

  • How to generate synthetic rows (raw(16) guid cols) in one SQL statement?

    We're populating a table containing two GUID columns:
    create table object
    ( object_guid raw(16) primary key
    , project_guid raw(16)
    )All object GUIDs are unique (thus the PK), and each object belongs to a given project (should be a FK to some project table). We want N objects / rows, belonging to only 100 projects, i.e. 1% of the rows of the object table belong to the project #1, 1% to #2, etc...
    Right now we're using about 25 lines of C++/OCI code to do that (one query doing a "select sys_guid() from dual", and using the generated GUIDs to do inserts into object), but I suspect it's possible to do this using a single SQL statement using mysterious connect by or some other Oracle SQL magic. (our OCI code does quite a few round-trips to do the equivalent).
    Would anyone please demonstrate how to generate the rows as explained above, and possibly describe how it works for the non-initiated?
    Thanks, --DD
    PS: I'm sure it can be done in PL/SQL as well, but I'm interested in a SQL version if one's possible.

    I've found two ways, both taking a few SQL statements, but somehow I think this ought to be possible without intermediary tables... I'm sure there's a better way.
    #1drop   table project_tmp;
    create table project_tmp
    as select rownum pid, sys_guid() guid from dual
    connect by level <= 100;
    drop   table object_tmp;
    create table object_tmp
    as select mod(rownum, 100) + 1 pid, sys_guid() guid from dual
    connect by level <= 1000;
    drop   table object;
    create table object
    as select o.guid object_guid, p.guid project_guid
    from object_tmp o, project_tmp p
    where o.pid = p.pid;
    drop table project_tmp;
    drop table object_tmp;#2:drop table project;
    create table project
    as select mod(rownum, 100) + 1 prj_id, sys_guid() guid from dual
    connect by level <= 100;
    drop table object;
    create table object
    as select mod(rownum, 100) + 1 prj_id, sys_guid() object_guid from dual
    connect by level <= 1000;
    alter table object add project_guid raw(16);
    update object o set o.project_guid = (select guid from project p where p.prj_id = o.prj_id);
    drop table project;
    alter table object drop column prj_id;Verification:select count(distinct project_guid) from object;
    select project_guid, count(OBJECT_GUID) from object group by project_guid;

  • Performance Issue using min() and max() in one SQL statement

    I have a simple query that selects min() and max() from one column in a table in one sql statment.
    The table has about 9 Million rows and the selected column has a non unique index. The query takes 10 secs. When i select min() and max() in separate statements, each takes only 10 msecs:
    This statement takes 10 secs:
    select min(date_key) , max(date_key)
    from CAPS_KPIC_BG_Fact_0_A
    where date_key != TO_DATE(('1900-1-1' ),( 'YYYY-MM-DD'))
    This statement takes 10 msecs:
    select min(date_key)
    from MYTABLE
    where date_key != TO_DATE(('1900-1-1' ),( 'YYYY-MM-DD'))
    union all
    select max(date_key) from MYTABLE
    Because the first statement is part of an autmatic generated SQL of an application, i can't change it and i have to optimize the data model. How can i speed up the first statement?

    I've ran similar query on a table that has 10 milliion rows, with an index on the date column
    This is what I have found:
    SQL> set timing on
      1  SELECT MIN(ID_DATE) MIN_DATE, MAX(ID_DATE) MAX_DATE
      2      FROM MY_DATE
      3*     WHERE ID_DATE != TO_DATE(('1900-1-1' ),( 'YYYY-MM-DD'))
    SQL> /
    MIN_DATE  MAX_DATE
    03-APR-76 06-JAN-02
    real: 43383
    SQL> SELECT MIN(ID_DATE) MIN_DATE FROM MY_DATE
      2   WHERE ID_DATE != TO_DATE(('1900-1-1' ),( 'YYYY-MM-DD'))
      3  UNION ALL
      4  SELECT MAX(ID_DATE) MAX_DATE FROM MY_DATE
      5   WHERE ID_DATE != TO_DATE(('1900-1-1' ),( 'YYYY-MM-DD'))
      6  /
    MIN_DATE
    03-APR-76
    06-JAN-02
    real: 20
    SQL> SELECT MIN_DATE, MAX_DATE FROM
      2  (SELECT MAX(ID_DATE) MAX_DATE FROM MY_DATE
      3  WHERE ID_DATE != TO_DATE(('1900-1-1' ),( 'YYYY-MM-DD')) ) A,
      4  (SELECT MIN(ID_DATE) MIN_DATE FROM MY_DATE
      5  WHERE ID_DATE != TO_DATE(('1900-1-1' ),( 'YYYY-MM-DD')) ) B
      6  /
    MIN_DATE  MAX_DATE
    03-APR-76 06-JAN-02
    real: 10
    SQL> My conculsion, there is nothing you can do to the tables that will improve that particular statement.
    Why can't you modify the application?

  • How to insert 22.5K rows in one sql statement in Oracle

    Hi Gurus,
    I have a one table with one column. I require to input 22.5k numbers example "08323459" in that table. Can anyone tell me how to insert those 22.5K numbers with one sql command.
    I am using PL/SQL client. And oracle version is 11G.

    If you have an Excel file, the simplest approach is generally to save the file as a CSV, copy it to the database server, create an external table that exposes the file as a table, and then write your INSERT by selecting the data from the external table.
    INSERT INTO permanent_table( column_name )
      SELECT column_name
        FROM external_tableAssuming you have SQL*Loader installed on your client machine, you could also use SQL*Loader to read the data in the file and load it into the database table.
    Justin

  • Getting Session ID via PL/SQL Statement

    Hi,
    I'd like to fill an item in my form with the current session id. Can I query this id via PL/SQL statement?
    Thank you

    i think you misunderstood.....
    i'd like to fill an item on my page with the current session id using a computation. this computation has to query this id.

  • Combine two select statements in one SQL statements

    I have the following two queries that I need to combine into one query, where it updates a single row at the same time.
    SELECT count(*) FROM database.USAGE WHERE SERVICE_TYPE = 'C' AND ACCOUNT = "4837"
    SELECT sum(minutes) FROM database.USAGE WHERE SERVICE_TYPE = 'DA' AND ACCOUNT = "4837"
    I want to insert the values of each select statement into two columns of the same row, as well as insert the account number from the select statement.
    After the query has been executed, the database row will look like this:
    ACCOUNT COUNT SUM
    4837 354 1039202
    I am looking for suggestions on how to:
    - either combine the two into one query
    - simply update each column with the value from each query by updating the row with the account value
    I am a SQL newbie - so I appreciate any assistance.
    Thanks,
    Tony

    Hi, Tony,
    When you're talking about changing the data in tables, "INSERT" means to add a new row, and you'll cause a lot of confusion if you use it to mean something else. So don't say
    "I want to insert the values of each select statement into two columns..."; use some other word, like:
    "I want to put the values of each select statement into two columns ..."
    If you happened to know that those two numbers were 354 and 1039202, you might say:
    UPDATE  table_x
    SET     a_count = 354
    ,       a_sum = 1039202
    WHERE   account = 4837;But you don't know the numbers; you want to have the query figure out what they are.
    In most places where you can use a literal (like 354 or 1039202), you can also use a scalar sub-query, a SELECT statement, enclosed in parentheses, that produces one column and (at most) one row.
    In your case, you can say:
    UPDATE  table_x
    SET     a_count = (SELECT count(*) FROM database.USAGE WHERE SERVICE_TYPE = 'C' AND ACCOUNT = 4837)
    ,       a_sum = (SELECT sum(minutes) FROM database.USAGE WHERE SERVICE_TYPE = 'DA' AND ACCOUNT = 4837
    WHERE   account = 4837;or, to make it more readable:
    UPDATE  table_x
    SET     a_count =
    ( SELECT count (*)
    FROM database.USAGE
    WHERE SERVICE_TYPE = 'C'
    AND ACCOUNT = 4837
    ,       a_sum =
    ( SELECT sum (minutes)
    FROM database.USAGE
    WHERE SERVICE_TYPE = 'DA'
    AND ACCOUNT = 4837
    WHERE   account = 4837;By the way, why are you using double-quotes around 4837? If it's a string, enclose it in single quotes. If it's a number (which I'm assuming in my code), don't enclose it in anything.
    WARNING: scalar sub-queries are somewhat like duct tape: they're extremely useful in certain places, and those places account for about 1% of their use. The other 99% of the time, there's a better way to do things, though the better way may require more expertise.

  • Counter in a Sql statement

    Hi,
    Given a column payment_type, where payment type varies, I need to count each time when the value of the payment_type changes and display the total count in the end.
    For example,
    payment_typ is 1 1 2 2 2 2 2 3 3 3 3 3 4. Total count should be 3. I need to traverse the values, capture the change and increment the counter.
    Any help is appreciated.
    Thanks

    Does this one do the job as well?:
    SQL> WITH t AS
         (SELECT     CASE
                        WHEN LEVEL <= 2
                           THEN 1
                        WHEN LEVEL <= 7
                           THEN 2
                        WHEN LEVEL <= 12
                           THEN 3
                        ELSE 4
                     END AS val
                FROM dual
          CONNECT BY LEVEL <= 13)
    SELECT t.*,
           LAG (val) OVER (PARTITION BY val ORDER BY NULL) l
      FROM t
    UNION ALL
    SELECT NULL,
           COUNT (*)
      FROM (SELECT t.*,
                   LAG (val) OVER (PARTITION BY val ORDER BY NULL) l
              FROM t)
    WHERE l IS NULL
           VAL          L
             1          
             1          1
             2          
             2          2
             2          2
             2          2
             2          2
             3          
             3          3
             3          3
             3          3
             3          3
             4          
                        4
    14 rows selected.(Maybe you want to substract 1 from result).

  • How to get row count of a sql query

    After firing a query, how can i get the number of records returned by the query from the database, it should be database indipendent.
    Statement stmt = conn.createStatement();
                      stmt.executeQuery(query);After this I want the number of row i.e. the number of records returned by the database.

    Number of rows in a ResultSet may be obtained with:
    ResultSet rs;
    int numRows=rs.last().getRow();
    I would have said this too, as a matter of fact I mentioned scrollable result sets in my post, but as I said, not all drivers support this, and he said he needed it to be database independent, so this method should not be used.

  • Script error - Inserting multiple rows in one SQL statement.

    Hi,
    Tried using INSERT ALL INTO command inside Script. But getting below error.
    Oracle <> error message for operation <OCIStmExecute>: <ORA-00928: missing SELECT keyword>.
    Same query with single insert statement runs fine without any issues.
    Oracle eg:
    INSERT ALL
        INTO item (title) VALUES ('title5')
        INTO item (title) VALUES ('title6')
        INTO item (title) VALUES ('title7')
    SELECT * FROM dual;
    Appreciate your suggestions.
    Thx

    Hi,
    Actual syntax is as below:
    INSERT ALL
      INTO suppliers (supplier_id, supplier_name) VALUES (1000, 'IBM')
      INTO suppliers (supplier_id, supplier_name) VALUES (2000, 'Microsoft')
      INTO suppliers (supplier_id, supplier_name) VALUES (3000, 'Google')
    SELECT * FROM dual;
    Now in your non working query, you have applied comma after first INTO statement.
    Please remove it.
    Thanks,
    Swapnil

Maybe you are looking for

  • Moving files from MacBook Pro to MacBook Air

    My MacBook Pro's display is all crapped out (can't even view on external monitor) and I'm trying to transfer files over to my new MacBook Air. How can I do this? Since there is no Firewire on my Air, I can't boot into target disk mode and just copy m

  • Keyboard for MacBook pro replaceable?

    On December 2007, my son bought a MacBook pro. Unfortunately on the way back to home the hair conditioner runs out and through the notebook case over the keyboard. Fundamentally: it is possible to exchange the (electronics of the) keyboard? Can I rep

  • What Power Adapter for 15" Aluminum PB?

    I have a 15"PB (Apple M9422LL/A) with a power adapter that's gone squirrelly on me. (There's apparently a loose wire at the junction between the brick and the wire that goes to the computer.) I'd like to get a compatible replacement, but the numbers

  • Move Portal Database to New Host

    Hi, We currently have EP7.0 installed and running on a single host.  We are running a DB2 database on AIX and would like to move just the database to a different host.  Can anyone advise the process by which we can do this? Thanks,

  • Failing to print report on some printers

    Hi All, I am hoping someone can assist with a problem I am having. I am printing a crystal report from a .Net Webservice. The code works perfectly on many sites and on my development environments. There is however one site that we are experiencing a