Help with count and sum query

Hi I am using oracle 10g. Trying to aggregate duplicate count records. I have so far:
SELECT 'ST' LEDGER,
CASE
WHEN c.Category = 'E' THEN 'Headcount Exempt'
ELSE 'Headcount Non-Exempt'
END
ACCOUNTS,
CASE WHEN a.COMPANY = 'ZEE' THEN 'OH' ELSE 'NA' END MARKET,
'MARCH_12' AS PERIOD,
COUNT (a.empl_id) head_count
FROM essbase.employee_pubinfo a
LEFT OUTER JOIN MMS_DIST_COPY b
ON a.cost_ctr = TRIM (b.bu)
INNER JOIN MMS_GL_PAY_GROUPS c
ON a.pay_group = c.group_code
WHERE a.employee_status IN ('A', 'L', 'P', 'S')
AND FISCAL_YEAR = '2012'
AND FISCAL_MONTH = 'MARCH'
GROUP BY a.company,
b.district,
a.cost_ctr,
c.category,
a.fiscal_month,
a.fiscal_year;
which gives me same rows with different head_counts. I am trying to combine the same rows as a total (one record). Do I use a subquery?

Hi,
Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
user610131 wrote:
... which gives me same rows with different head_counts.If they have different head_counts, then the rows are not the same.
I am trying to combine the same rows as a total (one record). Do I use a subquery?Maybe. It's more likely that you need a different GROUP BY clause, since the GROUP BY clause determines how many rows of output there will be. I'll be able to say more after you post the sample data, results, and explanation.
You may want both a sub-query and a different GROUP BY clause. For example:
WITH    got_group_by_columns     AS
     SELECT  a.empl_id
     ,     CASE
                    WHEN  c.category = 'E'
              THEN  'Headcount Exempt'
                    ELSE  'Headcount Non-Exempt'
            END          AS accounts
     ,       CASE
                    WHEN a.company = 'ZEE'
                    THEN 'OH'
                    ELSE 'NA'
            END          AS market
     FROM              essbase.employee_pubinfo a
     LEFT OUTER JOIN  mms_dist_copy             b  ON   a.cost_ctr     = TRIM (b.bu)
     INNER JOIN       mms_gl_pay_groups        c  ON   a.pay_group      = c.group_code
     WHERE     a.employee_status     IN ('A', 'L', 'P', 'S')
     AND        fiscal_year           = '2012'
     AND        fiscal_month          = 'MARCH'
SELECT    'ST'               AS ledger
,       accounts
,       market
,       'MARCH_12'          AS period
,       COUNT (empl_id)       AS head_count
FROM       got_group_by_columns
GROUP BY  accounts
,            market
;But that's just a wild guess.
You said you wanted "Help with count and sum". I see the COUNT, but what do you want with SUM? No doubt this will be clearer after you post the sample data and results.
Edited by: Frank Kulash on Apr 4, 2012 5:31 PM

Similar Messages

  • Help with supply and demand query using monthly buckets

    I'm working on a query bound for Discoverer which pulls the aggregated supply and demand for an item and buckets it into months. So for any given item, I need to show the item, onhand, cost, aggregated supply (planned orders, requisitions, pos), and aggregated demand (planned order demand, jobs) - all bucketed by months.
    The code below works okay to find all of the data for July, but I also need to show August and September. I'm thinking I could use a union but am reluctant because the query already runs kind of slow and I'm not sure if I'm on the right track.
    Database Server
    RDBMS : 10.2.0.3.0
    Oracle Applications : 11.5.9
    -Tracy
    select
          item.inventory_item_id, item.organization_code, item.item, item.description
        , item.make_buy,item.planner_code
        , planned.compile_designator, planned.order_type_text, sum(planned.quantity_rate)planned_total
        , planned.mrp_sugg_due_month
        , sum(job.required_quantity-job.quantity_issued)job_open, job.required_month
        , onhand.total_qoh
        , purchase.item_revision prev, purchase.promised_month, purchase.ship_to_organization_id 
        , sum((purchase.quantity-purchase.quantity_cancelled)-purchase.quantity_received)po_open  
        , req.item_revision rrev, req.destination_organization_id, req.org_id, req.need_by_month
        , sum((req.quantity-req.quantity_cancelled)-req.quantity_delivered)req_open
        , cost.item_cost,cost.cost
    from
    --item--
    (select mtl.inventory_item_id, mtl.segment1 item,mtl.description,decode(mtl.planning_make_buy_code,1,'Make',2,'Buy') make_buy
            ,mtl.organization_id, mtp.organization_code, mtl.planner_code
           ,to_char(add_months(sysdate,+1),'YYYY_MM')month1, to_char(add_months(sysdate,+2),'YYYY_MM')month2
           ,to_char(add_months(sysdate,+3),'YYYY_MM')month3
    from    inv.mtl_system_items_b mtl, inv.mtl_parameters mtp
    where    mtl.organization_id = mtp.organization_id
    )item,
    --planned orders - 3 months --
    (select compile_designator,organization_id,inventory_item_id,order_type_text,nvl(quantity_rate,0)quantity_rate,new_due_date
           ,to_char(trunc(new_due_date,'MM'),'YYYY_MM')mrp_sugg_due_month
    from   apps.mrp_orders_sc_v
    where  order_type_text in ('Planned order','Planned order demand')
    and    to_char(trunc(new_due_date,'MM'),'YYYY_MM') <= to_char(add_months(:Month,+2),'YYYY_MM')
    and    to_char(trunc(new_due_date,'MM'),'YYYY_MM') >=  to_char(:Month,'YYYY_MM')
    )planned,
    --jobs - 3 months--
    (select organization_id,wip_entity_name job, inventory_item_id,concatenated_segments,nvl(required_quantity,0)required_quantity
            ,nvl(quantity_issued,0)quantity_issued, date_required,to_char(trunc(date_required,'MM'),'YYYY_MM') required_month
            ,wip_entity_id,creation_date, wip_job_status
    from    apps.wip_requirement_ops_inq_v
    where   primary_item_id <>inventory_item_id
    and     wip_job_status not in ('Closed','Cancelled','Complete')
    and     to_char(trunc(date_required,'MM'),'YYYY_MM') <= to_char(add_months(:Month,+2),'YYYY_MM')
    and     to_char(trunc(date_required,'MM'),'YYYY_MM') >= to_char(:Month,'YYYY_MM')
    )job,
    --qty onhand--
    (select  inventory_item_id,organization_id,sum(nvl(transaction_quantity,0))total_qoh
    from     inv.mtl_onhand_quantities_detail
    group by inventory_item_id, organization_id
    )onhand,
    -- po - 3 months--
    (select pol.item_id, pol.item_revision, nvl(pll.quantity,0)quantity, nvl(pll.quantity_received,0)quantity_received
          , nvl(pll.quantity_rejected,0),nvl(pll.quantity_cancelled,0)quantity_cancelled,poh.segment1 po_num
           ,pll.promised_date, to_char(trunc(pll.promised_date,'MM'),'YYYY_MM')promised_month
           ,pll.shipment_num,pll.ship_to_organization_id 
    from   po.po_lines_all pol, po.po_headers_all poh, po.po_line_locations_all pll
    where  poh.po_header_id = pol.po_header_id
    and    pol.po_header_id = pll.po_header_id
    and    pol.po_line_id = pll.po_line_id
    and    pol.cancel_flag != 'Y'
    and    pol.item_id is not null
    and    to_char(trunc(pll.promised_date,'MM'),'YYYY_MM')<= to_char(add_months(:Month,+2),'YYYY_MM')
    and    to_char(trunc(pll.promised_date,'MM'),'YYYY_MM')>=  to_char(:Month,'YYYY_MM')
    )purchase,
    --reqs - 3 months--
    (select prh.segment1 req_number,nvl(prl.quantity,0)quantity,nvl(prl.quantity_delivered,0)quantity_delivered
           ,nvl(prl.quantity_cancelled,0)quantity_cancelled
           ,prl.destination_organization_id,prl.org_id,prl.item_id,prl.item_revision,prl.need_by_date
           ,to_char(trunc(prl.need_by_date,'MM'),'YYYY_MM')need_by_month
    from   po.po_requisition_headers_all prh, po.po_requisition_lines_all prl
    where  prh.requisition_header_id = prl.requisition_header_id(+)
    and    nvl(prl.cancel_flag,'N') !='Y'
    and    prh.authorization_status != 'CANCELLED'
    and    to_char(trunc(prl.need_by_date,'MM'),'YYYY_MM') <= to_char(add_months(:Month,+2),'YYYY_MM')
    and    to_char(trunc(prl.need_by_date,'MM'),'YYYY_MM') >=  to_char(:Month,'YYYY_MM')
    )req,
    --cost--
    (select msib.inventory_item_id,msib.organization_id,cqm.material_cost,cic.item_cost
    ,(case when cqm.material_cost=0 then cic.item_cost else cqm.material_cost end) cost, cqm.cost_group_id
    from inv.mtl_system_items_b msib
         ,(select cql.cost_group_id,cql.inventory_item_id,cql.organization_id,cql.layer_quantity,cql.material_cost,mp.organization_code
             from bom.cst_quantity_layers cql, inv.mtl_parameters mp
            where mp.default_cost_group_id = cql.cost_group_id) cqm
        ,bom.cst_item_costs cic
    where msib.inventory_item_id = cqm.inventory_item_id(+)
    and msib.organization_id = cqm.organization_id(+)
    and msib.inventory_item_id = cic.inventory_item_id(+)
    and msib.organization_id = cic.organization_id(+)
    )cost
    where item.inventory_item_id = job.inventory_item_id(+)
    and   item.organization_id = job.organization_id(+)
    and   item.month1 = job.required_month(+)  -- 2009_07 --
    and   item.inventory_item_id = onhand.inventory_item_id(+)
    and   item.organization_id = onhand.organization_id(+)
    and   item.inventory_item_id = purchase.item_id(+)
    and   item.month1 = purchase.promised_month(+)  -- 2009_07 --
    and   item.inventory_item_id = req.item_id(+)
    and   item.month1 = req.need_by_month(+)  -- 2009_07 --
    and   item.inventory_item_id = cost.inventory_item_id(+)
    and   item.organization_id = cost.organization_id(+)
    and   item.inventory_item_id = planned.inventory_item_id(+)
    and   item.organization_id = planned.organization_id(+)
    and   item.month1 = planned.mrp_sugg_due_month(+)  -- 2009_07 --
    and   item.make_buy = 'Buy'
    and   item.item in ('161309040','744L755','150-GFM') --test items --
    group by item.inventory_item_id,item.organization_code,item.item,item.description,item.make_buy,item.planner_code
          ,job.required_month ,onhand.total_qoh , purchase.item_revision,  purchase.promised_month
            ,purchase.ship_to_organization_id  ,cost.item_cost,cost.cost
           ,req.item_revision, req.destination_organization_id,req.org_id,req.need_by_month
           ,planned.compile_designator,planned.order_type_text,planned.mrp_sugg_due_month
    order by item.organization_code,item.item

    Hi,
    Six things:
    (1) Where are the one-to-many relationships between your tables? If a single row in mtl can match two (or more) rows in mrp, and can also match two (or more) rows in wip, then it looks like, when you join both of them them, you'll have a chasm trap, that is, you'll get all the matching rows from mrp paired with all matching rows from wip. Are you sure your existing query is producing the right results?
    Are there one-to-many relationships with the other tables in your original query?
    (2) Are your DATEs always at midnight? If not, avoid using BETWEEN and LAST_DAY for DATE comparisons: otherwise you'll miss everything between 00:00:01 and 23:59:59 on the last day.
    That is, instead of
    and     mrp.new_due_date(+) BETWEEN :Month AND LAST_DAY(ADD_MONTHS(:Month,2))ypou should say
    and       mrp.new_due_date (+)     >= :Month
    and       mrp.new_due_date (+)     <  ADD_MONTHS (:Month, 3)(3) The basic way to pivot the months of mrp_due_date is:
    SELECT    ...
    ,       NVL ( SUM ( CASE
                     WHEN  mrp.new_due_date >= :month
                     AND   mrp.new_due_date < ADD_MONTHS (:month, 1)
                     THEN  mrp.quantity_rate
                    END
               , 0
               )          AS mrp_qty_0
    ,       NVL ( SUM ( CASE
                     WHEN  mrp.new_due_date >= ADD_MONTHS (:month, 1)
                     AND   mrp.new_due_date <  ADD_MONTHS (:month, 2)
                     THEN  mrp.quantity_rate
                    END
               , 0
               )          AS mrp_qty_1When you do this, do not GROUP BY TRUNC (mrp.new_due_date, 'MM').
    The code above does two months: I'm sure you get the idea for how to do more.
    To get dynamic column headings (such as Jun_2009 or "2009-06" instead of the generic mrp_qty_o) requires dynamic SQL. The best way to do dynamic SQL depends on the tool that is producing the query (e.g. SQL*Plus). What are you using? Are you willing to change, if it helps?
    (4) Displaying separate columns from one row as a single column on multiple rows is called unpivoting. How badly do you want to do that? Your query would be simpler and faster if the output had only one row per group (rather than one row for mrp_qty and another row for wip_wty). That one row could have six columns (e.q. June_mrp, June_wip, July_mrp, July_wip, August_mrp and August_wip) instead of three. Depending on your front-end tool, you might even be able to wrap the single row of output so that it always appeared as two rows, each with three columns.
    (5) Sorry I told you to do
    and     mrp.order_type_text(+) in (...)I never use the + outer-join notation any more, so I forgot about the ORA-01719 error. There's no problem having an outer-join condition like that using ANSI notation. (One more reason to switch.)
    (6) As you noticed, this site doesn't like to print the &lt;&gt; inequality operator, even inside tags.
    Use the equivalent != operator instead, when posting on this site.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Hi! Everyone, I have some problems with JOIN and Sub-query; Could you help me, Please?

    Dear Sir/Madam
    I'm a student who is interested in Oracle Database and
    I have some problems with JOIN and Sub-query.
    I hope so many of you could help me.
    if i use JOIN without sub-query, may it be faster or not?
    SELECT field1, field2 FROM tableA INNER JOIN tableB
    if i use JOIN with sub-query, may it be faster or not?
    SELECT field1,field2,field3 FROM tableA INNER JOIN (SELECT field1,field2 FROM tableB)
    Thanks in advance!

    Hi,
    fac30d8e-74d3-42aa-b643-e30a3780e00f wrote:
    Dear Sir/Madam
    I'm a student who is interested in Oracle Database and
    I have some problems with JOIN and Sub-query.
    I hope so many of you could help me.
    if i use JOIN without sub-query, may it be faster or not?
    SELECT field1, field2 FROM tableA INNER JOIN tableB
    if i use JOIN with sub-query, may it be faster or not?
    SELECT field1,field2,field3 FROM tableA INNER JOIN (SELECT field1,field2 FROM tableB)
    Thanks in advance!
    As the others have said, the execution plan will give you a better idea about which is faster.
    If you're trying to see how using (or not using) a sub-query affects performance, make the rest of the queries as similar as possible.  For example, include field3 in both queries, or ignore field3 in both queries.
    In this particular case, I guess the optimizer would do the same thing either way, but that's just a guess.  I can't see your execution plans.
    In general, simpler code is faster, and better in other ways, too.  In this case
    tableB
    is simpler than
    (SELECT field1, field2  FROM tableB)
    Why do you want a sub-query in this example?

  • COUNT() and SUM() function it not working in XDO file.

    Hi ,
    I am getting one error. Count and sum function not working proper.
    For example :
    Department 10 have 3 employee and total salary is 8750. But my report returning total employee 1 and total salary 5000
    10
    Ename Sal
    KING 5000
    CLARK 2450
    MILLER 1300
    ==================
    total employee : 1
    total salary : 5000
    Kindly help me solve this problem.
    <dataTemplate name="TEXT">
    <properties>
    <property value="upper" name="xml_tag_case" />
    </properties>
    <lexicals>
    </lexicals>
    <dataQuery>
    <sqlstatement name="Q_TEMP">
    <![CDATA[SELECT DEPTNO,DNAME,LOC FROM DEPT]]>
    </sqlstatement>
    <sqlstatement name="Q_TEMP1">
    <![CDATA[SELECT ENAME,HIREDATE,SAL FROM EMP WHERE DEPTNO = :DEPTNO]]>
    </sqlstatement>
    </dataQuery>
    <datastructure>
    <GROUP name="G_1" source="Q_TEMP">
    <element value="DEPTNO" name="DEPTNO" />
    <element value="DNAME" name="DNAME" />
    <element value="LOC" name="LOC" />
    <GROUP name="G_2" source="Q_TEMP1">
    <element value="ENAME" name="ENAME" />
    <element value="SAL" name="SAL" />
    <element value="G_2.ENAME" name="TOTL_DETAILS" dataType="number" function="COUNT()" />
    <element value="G_2.SAL" name="TOTL_SAL" function="SUM()"/>
    </GROUP>
    </GROUP>
    </datastructure>
    </dataTemplate>
    Thanks
    Yudhi

    Please have the data structure as below:
    <datastructure>
    <GROUP name="G_1" source="Q_TEMP">
    <element value="DEPTNO" name="DEPTNO" />
    <element value="DNAME" name="DNAME" />
    <element value="LOC" name="LOC" />
    <GROUP name="G_2" source="Q_TEMP1">
    <element value="ENAME" name="ENAME" />
    <element value="SAL" name="SAL" />
    *</GROUP>*
    *<element value="G_2.ENAME" name="TOTL_DETAILS" dataType="number" function="COUNT()" />*
    *<element value="G_2.SAL" name="TOTL_SAL" function="SUM()"/>*
    *</GROUP>*
    </datastructure>
    Aggregate functions to be placed at the level you require it. Here you need at G_1, so place it there.

  • Help with writing and retrieving data from a table field with type "LCHR"

    Hi Experts,
    I need help with writing and reading data from a database table field which has a type of "LCHR". I have given an example of the original code but don't know what to change it to in order to fix it and still read in the original data that's stored in the LCHR field.
    Basically we have two Function modules, one that saves list data to a database table and one that reads in this data. Both Function modules have an identicle table which has an array of fields from type INT4, CHAR, and type P. The INT4 field is the first one.
    Incidentally this worked in the 4.7 non-unicode system but is now dumping in the new ECC6 Unicode system.
    Thanks in advance,
    C
    SAVING THE LIST DATA TO DB
    DATA: L_WA(800).
    LOOP AT T_TAB into L_WA.
    ZDBTAB-DATALEN = STRLEN( L_WA ).
    MOVE: L_WA to ZDBTAB-RAWDATA.
    ZDBTAB-LINENUM = SY-TABIX.
    INSERT ZDBTAB.
    READING THE DATA FROM DB
    DATA: BEGIN OF T_DATA,
                 SEQNR type ZDBTAB-LINENUM,
                 DATA type ZDBTAB-RAWDATA,
               END OF T_TAB.
    Select the data.
    SELECT linenum rawdata from ZDBTAB into table T_DATA
         WHERE repid = w_repname
         AND rundate = w_rundate
         ORDER BY linenum.
    Populate calling Internal Table.
    LOOP AT T-DATA.
    APPEND T_DATA to T_TAB.
    ENDLOOP.

    Hi Anuj,
    The unicode flag is active.
    When I run our report and then to try and save the list data a dump is happening at the following point
    LOOP AT T_TAB into L_WA.
    As I say, T_TAB consists of different fields and field types whereas L_WA is CHAR 800. The dump mentions UC_OBJECTS_NOT_CONVERTIBLE
    When I try to load a saved list the dump is happening at the following point
    APPEND T_DATA-RAWDATA to T_TAB.
    T_DATA-RAWDATA is type LCHR and T_TAB consists of different fields and field types.
    In both examples the dumps mention UC_OBJECTS_NOT_CONVERTIBLE
    Regards
    C

  • Count and Sum running total

    Can i sum and couunt running total in formula?.
    Please let me know.

    Hey, we can do count and sum functions in Running total.
    These functions are available in crystal reports for  summary fields.
    We can create  the running total based on the type of summary like Sum, count, max, min, distinct count, etc.
    We can do Evaluation for each record or on group or on each field  and also be done by writing a formula.
    We can  do count or sum by manual running total by writing a formula in the formula workshop.
    Based on our requirement we can use both functionalities.
    Please let me know  if you have any queries.
    Regards,
    Naveen.

  • MOVED: [Athlon64] Need Help with X64 and Promise 20378

    This topic has been moved to Operating Systems.
    [Athlon64] Need Help with X64 and Promise 20378

    I'm moving this the the Administration Forum.  It seems more apporpiate there.

  • Help with looping and counting

    i am in a CS 1 class and need help with this loop
    /*Write a program that will allow the user to enter a character
              until the capital letter Z is entered
         The program should count the number of letters entered
              and print the total after the loop is completed*/
    here is what i have it doesn't end nor does it count and i don't know hwo to make it count also i suck at do..while loops hehe
    char b,Z=0;
              Scanner a = new Scanner(System.in);
         do
                   System.out.print("Enter a letter: "+"\n");
                   b=a.next().charAt(0);
              while (b !=Z);
    i know that its not even close to being right just help me out here
    Edited by: purplesmurf on Nov 14, 2008 7:25 PM

    The following program will count the number of chacters entered until Z is enetered.
    import java.io.*;
    class count
         public static void main(String[] args)throws IOException
              char ch;
              int cnt=0;
              DataInputStream br=new DataInputStream(System.in);
              do
              System.out.print("Enter a character:");
              ch=(char)br.read();
              if(ch!='Z')
                   cnt++;
              else
                   break;
              }while((ch=(char)br.read())!='Z');
              System.out.println("The Number of entered characters are:"+cnt);
    }

  • A problem with LOV and my query. Help to solve, please...

    Hello!
    Here is a query:
    SELECT FULLNAME||', '||(SELECT NAMEOFGROUP||', '||(SELECT CITY FROM CITY WHERE PRKEY=TLL.CITY) FROM GROUPS TLL WHERE PRKEY=TL.GROUPOF) t ,PRKEY r FROM MINEUSERS TL
    In SQL DEVELOPER it works fine. But in APEX - when I try to save my "SELECT LIST" - it falls with error - "If your query contains an in-line query, the first FROM clause in the SQL statement must not belong to the in-line query."
    How can I reassemble my query to fix this problem - I have no idea... :(
    Thanks

    You may create a pipelined function returning two values, display and return, to return
    the result from your query. After that, your LOV should work. See example here:
    http://htmldb.oracle.com/pls/otn/f?p=31517:146
    Denes Kubicek
    http://deneskubicek.blogspot.com/
    http://htmldb.oracle.com/pls/otn/f?p=31517:1
    -------------------------------------------------------------------

  • Help with re-writing this query

    Dear experts;
    create table t2
      ID varchar2(1000),
      name varchar2(1000),
       place varchar2(1000)
    create table mappingt2
      grades varchar2(1000)
      individual varchar2(1000)
    insert into t2 values ('James', 'John', 'newyork');
    insert into t2 values ('Linda', 'James', 'London');
    insert into t2 values ('Alex', 'kim', 'Mexico');
    insert into t2 values ('karen', 'Jack', 'Tunis');
    insert into t2 values ('CC', 'Jack', 'Peru');
    insert into t2 values ('Linda', 'James', 'Germany');
    insert into mappingt2 values ('A', 'James');
    insert into mappingt2 values ('C', 'Kim');
    insert into mappingt2 values ('C', 'Linda');
    insert into mappingt2 values ('B', 'CC');I have the following query below
    SELECT (select grades from mappingt2 t
       where t.individual =  pt.ID) as current_grade
          ,(select grades from mappingt2 ty
       where ty.individual =  pt.name) alt_grade
          ,pt.place
      FROM t2 ptI was just wondering whether this query can be better written. All help is appreciated. Thank you

    user13328581 wrote:
    Hi Frank, Tom Kyte claims sub scalar queries is usually betterHe didn't say usually he said if you want the first row faster
    >
    if your goal is to optimize your query for initial response time, you may want to use the former query, with the scalar subquery, because Oracle Database would have to get just the first row from DEPT, run the scalar subquery (select count...) against EMP to get the count, and then return it. The process for returning that first row would be very fast.
    >
    The corollary to this that was not explicitly mentioned in the article that I can see is that this probably comes at the expense of the time taken to return all the rows which can then take longer.

  • Help Using Count and SQL statements

    Hello
    This problem has been bugging me incesantly and I would be reaaaaaaally grateful if someone could help here
    I want to create query that woud count the number of times a certain unedited word would be matched against different edited words
    This query works well in MS ACCess but not in java
    query =" SELECT Count(*) AS WordCount, Segmentations.EditedWord FROM [select Segmentations.EditedWord FROM Segmentations where Segmentations.UneditedWord = '"+Word+"']. AS c GROUP BY Segmentations.EditedWord";
    I've tried removing the Segmentations. and changing it to
    query =" SELECT Count(*) AS WordCount, EditedWord FROM [select EditedWord FROM Segmentations where UneditedWord = '"+Word+"']. AS c GROUP BY EditedWord";
    But still nothing
    I think that is due to the fact that you can't call Count(*) and another field at the same time
    pleas eif anyone knows a way around this send it ASAP
    thanx

    Why not use,
    query = "SELECT Count(*) AS WordCount, EditedWord FROM Segmentations WHERE  UneditedWord = ? GROUP BY EditedWord"and use PreparedStatement to optimize.
    HTH

  • Help with counter

    Hi everyone,
    I am writing this page for users to register and to login, but the problem i have is knowing who are the most active users.
    I am trying to do this with a hit counter, as you can see in my last "if", but is not working as it should be.
    Can somebody help with this.
    thanks.
    <html>
    <head>
                     <title>   2  </title>
    </head>
    <body>
    <body bgcolor="#FFFFFF">
    <center>
    <br>
    <%
      Cookie[] cookies = request.getCookies();
      if (cookies == null){
        cookies = new Cookie[0];
      Cookie c = new Cookie("users","");
      response.addCookie(c);
      String username  = request.getParameter("username");
      String password = request.getParameter("password");
      Cookie newuser = null;
      if (username!=null && password!=null && username.length()>0) {
        newuser = new Cookie(username,password);
        response.addCookie(newuser);
          for (int i=0; i<cookies.length; i++) {
          if (newuser!=null && newuser.getName().equals(cookies.getName())){
    newuser = null;
    out.println("><BR> <H3>" + "That username already exists, please enter another."+"<BR> </H3>");
    if (newuser != null){
    out.println("<H3> Welcome new user: <BR>"+newuser.getName()+":\t"+ newuser.getValue()+"<BR> </H3>");
    int counter = 0;
    if (request.getParameter("registereduser") != null){
         for (int i=0; i<cookies.length; i++) {
              if (request.getParameter("registereduser").equals( cookies[i].getName() ) ){
         out.println("><BR> <H3>" + "Welcome again, "+ cookies[i].getName()+counter++"<BR> </H3>");
    %>
    </center>
    </body>
    </html>

    I'm trying to do it this way:
    I have declared an static counter to do the task, and is incrementing everytime the page is visited, but,
    I want that depending of the user, it will print a different output, for example:
    user "a", visted 3 times,
    or user "b" visited 8 times.
    I was thinking in a counter for each user, and to save it and restore it every time the user visits.
    how can i do that?
    <%! static int staticCounter = 1; %>
    <%
    if (request.getParameter("registereduser") != null){
               for (int i=0; i<cookies.length; i++) {
                     if (request.getParameter("registereduser").equals( cookies.getName() ) ){
         out.println("><BR> <H3>" + "Welcome again, "+ cookies[i].getName()+staticCounter++"<BR> </H3>");
    %>

  • Help with Converting an Access query

    Hello:
    First time poster and would appreciate some help in converting this Access query into T-SQL so I can use in a Stored Procedure. I don't need help in resolving the syntax for the variables as parameter in the second query, but stuck in writing the first query
    in T-SQL . I assume I need some type of nested query with a left join to another query in T-SQL. 
    How do I convert this from Access into MS-SQL
    SELECT TBL_MONTH.L_Month, TBL_MONTH.L_MonthName
    FROM TBL_MONTH LEFT JOIN qry_MonthCheck ON TBL_MONTH.L_Month = qry_MonthCheck.L_Month
    WHERE (((qry_MonthCheck.L_Month) Is Null));
    qryMonthCheck in Access is defined as
    SELECT TBL_MONTH.L_Month, TBL_SIGNOFF.SO_YEAR, TBL_SIGNOFF.SO_USER, TBL_SIGNOFF.SO_LOCATION
    FROM TBL_MONTH RIGHT JOIN TBL_SIGNOFF ON TBL_MONTH.L_Month = TBL_SIGNOFF.SO_MONTH
    WHERE (((TBL_SIGNOFF.SO_YEAR)=[forms]![frm_signoff]![cboyear]) AND ((TBL_SIGNOFF.SO_LOCATION)=[Tempvars]![tmpVarUserLOC]));

    It is very much up to personal taste. For tables I use no prefix at all. Or suffix. I prefer plural: categories, products, etc. For junction tables, I drop the plural in the first entity, for instance productcategories. As for the case, many people prefer
    initial uppercase, while I go for lowercase only. But initial uppercase has its points, particularly in documentation. I am a staunch advocate of using case-sensitive collation for metadata. I don't see any point in mixing productcategories, Productcategories,
    ProductCategories etc. That can only cause confusion.
    As for either entities, I don't use views much, and I don't have any prefix for these either. In fact, several views I've been involved used to be tables once upon a time.
    If you want to add a marker to the object name, I recommend using a suffix. It is much easier to find objects in the version control system and other browser, when not everything is cluttered on the same letter. For instance, I typically add _sp at the end
    of stored procedure names.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Please help with Database and JTable.

    The class listed below is for a JTable. The main in this class is for testing only, when complete main will reside elsewhere. I need to know how to make this JTable universal. How can I set it up so that when called in a main and passed parameters it will display the information contained in that users database?? Again it must be universal so no matter who uses it, it will perform the same on all database's.
    Here's the code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class DisplayTable extends JFrame{
    public DisplayTable() {
         JFrame jf = new JFrame("Window Title");
              jf.setSize(1100,700);
              jf.setLocation(25,50);
              jf.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e){
                        System.exit(0);}
         TableModel tm = new AbstractTableModel(){
              String[][] data = { {"How to get database data??"}};
              String[] headers = {"How to get database headers??"};
              public int getRowCount() {return data.length;}
              public int getColumnCount() {return headers.length;}
              public Object getValueAt(int r, int c) {return data[r][c];}
              public String getColumnName(int c) {return headers[c];}
         JTable jt = new JTable(tm);
         JScrollPane jsp = new JScrollPane(jt);
              jf.getContentPane().add(jsp, BorderLayout.CENTER);
              jf.setVisible(true);
    public static void main(String args[]){
         DisplayTable dt = new DisplayTable(Database Parameters to be given here);

    You could generalize it, but it gets tricky to deal with the data types and if the JTable is editable because you would read the DB table data at run time. Using the ResultSetMetaData, you would be able to find the column type too. But, how can we cast an object at run-time?
    Below, I have provided an overview as of doing a read-only (all-strings version) of it. You may have some ideas from there.
    The database parameters that you pass to the constructor would tell the model where to connect and which DB table to read the data from. Couple of options:
    1. You can read the data in the constructor of DisplayTable into final variables and have the inner class (model) set its data and headers from those variables.
    Or
    2. Pull out the model as a separate class extending AbstractTableMode. Doing this, you can pass on the DB information to the model and have the model talk to the DB.
    And, I would use dynamic datastructures like Vector or List instead of arrays.
    You would have the following logic wherever you chose to talk to the DB:
    I am assuming that you are trying to read a complete DB table into your JTable (or may be you would pass a SELECT-query alongwith your DB information). Whatever may be the case, you would execute a select- to the DB and get a resultset back. Using that you would be able to get the ResultSetMetaData, which will give you the column count and column names. You may chose to use these column names as the header names for your JTable. With the column count you would query every row to get the object at each column.
    Here is a sample model:
    class MyModel extends AbstractTableModel {
        ArrayList columnNames = new ArrayList();
        ArrayList data = new ArrayList();
        MyModel(<DB Info>) {
            // Use the DB info and get the resultset
            ResultSetMetaData rsm = rs.getMetaData();
            int col = rsm.getColumnCount();
            for(int i=1; i<=col; i++) {
                columnNames.add(rsm.getColumnName(i));
            // Read the data
            while(rs.next()) {
                ArrayList row = new ArrayList();
                data.add(row);
                for(int j=1; j<=col; j++) {
                    // Here is the tricky part which I did not figure yet. For now, I am reading in all as Strings.
                    row.add(rs.getObject(j).toString());
        public String getColumnName(int c) {
            return (String)columnNames.get(c);
        public int getColumnCount() {
            return columnNames.size();
        public Object getValueAt(int r,int c) {
            ArrayList row = (ArrayList)data.get(r);
            return (String)row.get(c);
        public int getRowCount() {
            return data.size();
    }If you figured a way to handle run-time casting, please let us know.
    HTH.
    Vijay

  • I am a rookie and need help with max and min values

    Hello all, i am into this intro to java class. my assignment is to write a program that prompts the user for two integers and then prints the sum, difference, average, product , distance (absolute value of the difference) Maximum(largest of the two) and Minimum(smallest fo the two) here is my code so far
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.lang.Math;
    public class Sample4
       public static void main(String[] args) throws IOException
          try // attempt the following
    {           // create the stream to read from
    InputStreamReader istream = new InputStreamReader(System.in);   // create a buffer to hold the stream
    BufferedReader console = new BufferedReader(istream);           // prompt the user
          System.out.println("Enter a number please");              // get input as a string
          String input = console.readLine();                        // convert to an integer
          int num1 = Integer.parseInt(input);
          System.out.println("Enter a number please");              // get input as a string
          String input2 = console.readLine();                       // convert to an integer
          int num2 = Integer.parseInt(input2);
          int sum = num1 + num2;                                    // get the sum of the two inputs
          int difference = num1 - num2;                             // get the difference of the two inputs
          int product = num1 * num2;                                // get the product of the two inputs
          int average = sum / 2;                                    // get the average of the two inputs
          int abs = Math.abs(difference);                           // get the absolute value of the two inputs
              // new section
                 // display the number
          System.out.println("The total sum = " + sum);
          System.out.println("The total difference = " + difference);
           System.out.println("The total product = " + product);
           System.out.println("The total average = " + average);
           System.out.println("The total absolute value = " + abs);
    } // if something breaks, catch the exception
    catch (IOException e)
       System.out.println(e); // displays the exception
       System.exit(1);  // quits the program
    }what will be the right syntax or code to find the MAX and MIN values of two numbers a User Inputs, hope someone can help with this. thank you for your help.

    Thanks alot man, sheesh i do not know why my book
    doesnt give me all the static methods. but i do really
    appreciate your help. peaceA complete list of the java.lang.Math methods can be found at http://java.sun.com/j2se/1.4/docs/api/java/lang/Math.html
    btw,
    max(a, b) == (a > b) ? a : b
    min(a, b) == (a < b) ? a : b

Maybe you are looking for