Issue returning a count of rows in a SELECT QUERY...

I am working in Oracle 11.2g and I have a query where I want to return the count of DAILY records as well as WEEKLY records for specific marketers.
Here is my query:
Select     Mka_Mktr_No, 
          Case When Rat_Freq_Cd = 'D' Then Count(*) Else 0 End DailyCount,
          case when Rat_Freq_Cd = 'W' then count(*) Else 0 End WeeklyCount
        From     Marketer_Account, Acct
        Where     Mka_Exp_Dt >= '01-NOV-2012'
        And     Mka_Eff_Dt <= '30-NOV-2012'
        and     rat_acct_no = mka_acct_no
        And     Rat_Usage_Cd = 'P'
        and rat_freq_cd != 'M'
        Group By Mka_Mktr_No, Rat_Freq_Cd
        Order By Mka_Mktr_No;I would prefer to have the results show up on the SAME row, but instead I get the following results:
MKA_MKTR_NO            DAILYCOUNT             WEEKLYCOUNT           
10005                  68                     0                     
10005                  0                      2                      Note how it shows each count on a seperate row. Is there a way to tweak the query to show the counts on the same row:
MKA_MKTR_NO            DAILYCOUNT             WEEKLYCOUNT           
10005                  68                     2       and not have two seperate rows?
Many thanks,
Sean

Don't group by rat_freq_cd
SQL> with test_data as
  2      (
  3      select 1 mka_mktr_no, 'W' rat_freq_cd from dual union all
  4      select 1 mka_mktr_no, 'W' rat_freq_cd from dual union all
  5      select 1 mka_mktr_no, 'D' rat_freq_cd from dual union all
  6      select 2 mka_mktr_no, 'D' rat_freq_cd from dual union all
  7      select 2 mka_mktr_no, 'W' rat_freq_cd from dual union all
  8      select 2 mka_mktr_no, 'W' rat_freq_cd from dual union all
  9      select 2 mka_mktr_no, 'D' rat_freq_cd from dual union all
10      select 2 mka_mktr_no, 'D' rat_freq_cd from dual union all
11      select 2 mka_mktr_no, 'D' rat_freq_cd from dual union all
12      select 3 mka_mktr_no, 'D' rat_freq_cd from dual union all
13      select 3 mka_mktr_no, 'D' rat_freq_cd from dual union all
14      select 3 mka_mktr_no, 'W' rat_freq_cd from dual union all
15      select 3 mka_mktr_no, 'D' rat_freq_cd from dual union all
16      select 3 mka_mktr_no, 'D' rat_freq_cd from dual union all
17      select 3 mka_mktr_no, 'W' rat_freq_cd from dual
18      )
19  select
20      mka_mktr_no,
21      count(case when rat_freq_cd = 'D' then rat_freq_cd end) dailycount,
22      count(case when rat_freq_cd = 'W' then rat_freq_cd end) weeklycount
23  from
24      test_data
25  group by mka_mktr_no;
MKA_MKTR_NO DAILYCOUNT WEEKLYCOUNT
          1          1           2
          2          4           2
          3          4           2

Similar Messages

  • Count the rows which are selected ?

    Hi Experts,
    I need help.My requirement is:
    I am having a table which can be multiple selected. But there are two buttons attached to it.Edit and Delete.For Delete I want the Multiple Selection not for EDit.So, If i will click the Edit after multiple selection of the rows.How i can give pop-up that multiple edit is not possible?Means I want to count the rows which are selected how to do that?
    Please guide me.
    Urgent need
    Regards
    Nutan

    Hi Nutan,
    Marcel is right about backend. However I might have an idea once I am developing a quiet similar solution. I would like to ask you to explain with more detail. It seems you have two requirements in one question.
    Regards,
    Gilson

  • Needs  help to retrive the last row in a  select query without using rownum

    Hi ,
    i need to retrive the last row from the select sub query without using rownum.
    is there any other way to retrive the last row other than the below query.
    is that the ROWNUM=1 will always retrive the 1 row of the select query ?
    select from*
    *(select ename from employee where dept_id=5 order by desc) where rownum=1;*
    Please advise.
    thanks for your help advance,
    regards,
    Senthur

    957595 wrote:
    Actually my problem is ithat while selecting the parents hiearchy of the child data using
    CONNECT BY PRIOIR query
    I need the immediate parent of my child data.
    For example my connect BY query returns
    AAA --- ROOT
    BBB --PARENT -2
    CCC --PARENT-1
    DDD IS my input child to the connect by query
    Immediate parent of my child data "DDD" ---> CCC(parent -1)
    i want the data "CCC" from the select query,for that i am taking the last row of the query with rownum.
    I got to hear that using ROWNUM to retrive the data will leads to some problem.It is a like a magic number.I am not sure what the problem will be.
    So confusing with using this rownum in my query.
    Please advice!!!It's not quite clear what you're wanting, but perhaps this may help?
    you can select the PRIOR values to get the parent details if you want...
    SQL> ed
    Wrote file afiedt.buf
      1  select empno, lpad(' ',(level-1)*2,' ')||ename as ename, prior empno as mgr
      2  from emp
      3  connect by mgr = prior empno
      4* start with mgr is null
    SQL> /
         EMPNO ENAME                                 MGR
          7839 KING
          7566   JONES                              7839
          7788     SCOTT                            7566
          7876       ADAMS                          7788
          7902     FORD                             7566
          7369       SMITH                          7902
          7698   BLAKE                              7839
          7499     ALLEN                            7698
          7521     WARD                             7698
          7654     MARTIN                           7698
          7844     TURNER                           7698
          7900     JAMES                            7698
          7782   CLARK                              7839
          7934     MILLER                           7782
    14 rows selected.(ok, not the best of examples as the mgr is already known for a row, but it demonstrates you can select prior data)

  • Guidance on use of "COUNT(*) OVER () * 5" in a select query.

    Hello Friends,
    I was reading one article, in which one table was created for demo. Following was the statements for there.
    CREATE TABLE source_table
    NOLOGGING
    AS
    SELECT ROWNUM AS object_id
    , object_name
    , object_type
    FROM all_objects;
    INSERT /*+ APPEND */ INTO source_table
    SELECT ROWNUM (COUNT(*) OVER () * 5)+ AS object_id
    , LOWER(object_name) AS object_name
    , SUBSTR(object_type,1,1) AS object_type
    FROM all_objects;
    INSERT /*+ APPEND */ INTO source_table
    SELECT ROWNUM (COUNT(*) OVER() * 10)+ AS object_id
    , INITCAP(object_name) AS object_name
    , SUBSTR(object_type,-1) AS object_type
    FROM all_objects;
    Can anyone please tell me the purpose of *"ROWNUM + (COUNT(*) OVER () * 5)"* in above 2 insert statements, or suggest me some document on that.
    I don't know about its usage, and want to learn that..
    Regards,
    Dipali..

    The insert statements that you have listed are using Oracle Analytic Functions. Some examples of these functions can be found here: [Oracle Analytic Functions|http://www.psoug.org/reference/analytic_functions.html|Oracle Analytic Functions]
    Effectively what that says is the following:
    1. "COUNT(*) OVER ()" = return the number of rows in the entire result set
    2. Multiply that by 5 (or 10 depending on the insert)
    3. Add the current ROWNUM value to it.
    This can be shown with a simple example:
    SQL&gt; edit
    Wrote file sqlplus_buffer.sql
      1  SELECT *
      2  FROM
      3  (
      4     SELECT ROWNUM r,
      5             (COUNT(*) OVER ()) AS ANALYTIC_COUNT,
      6             5,
      7             ROWNUM + (COUNT(*) OVER () * 5) AS RESULT
      8     FROM all_objects
      9  )
    10* WHERE r &lt;= 10
    SQL&gt; /
             R ANALYTIC_COUNT          5     RESULT
             1          14795          5      73976
             2          14795          5      73977
             3          14795          5      73978
             4          14795          5      73979
             5          14795          5      73980
             6          14795          5      73981
             7          14795          5      73982
             8          14795          5      73983
             9          14795          5      73984
            10          14795          5      73985
    10 rows selected.
    SQL&gt; SELECT COUNT(*) from all_objects;
      COUNT(*)
         14795Hope this helps!
    Note the the statements you provided will not actually execute because of the extra "+" signs on either side. I have removed them.

  • Convert columns to rows by a select query

    I have a table with 10 columns. Pk is combination of 3 columns, let us say A, B and C. I need a select query which returns 7 rows with four columns each let us say A,B,C and D where D contains the value of non PK column. i.e. for first row, D will contain value of fourth column of the table, for second row, D will contain fifth column of the table and so on.
    Please help.

    Maybe NOT TESTED!
    select col_a,col_b,col_c,column_4 col_d
      from (select col_a,col_b,col_c,col_d,col_e,col_f,col_g,col_h,col_i,col_j
              from the_table
    unpivot include nulls (column_4 for source_column in (col_d as 'col_d',
                                                          col_e as 'col_e',
                                                          col_f as 'col_f',
                                                          col_g as 'col_g',
                                                          col_h as 'col_h',
                                                          col_i as 'col_i',
                                                          col_j as 'col_j'
                          )Regards
    Etbin

  • How do I get last 15 rows from a select query

    Hello,
    I am writing a query, and I need to filter the last 15 rows of from the select query.
    For example: Select id, name,join_date from emp order by join_date;
    So I need to get the last 15 rows from emp table so that we can who are the last 15 employees joined the organization. I want to show the result in ascending order, otherwise I would have taken first 15 rows with order by clause as descinding order.
    Thanks in advance,
    Param.

    SQL> select ename, join_date from test222
    2 where rownum < 6
    3 order by join_date
    4 /
    ENAME JOIN_DATE
    CNC5461177794 14-FEB-02
    OR91551178218 14-FEB-02
    TUB9894676495 14-FEB-02
    SG15431177117 14-FEB-02
    PIB9384674017 14-FEB-02
    SQL> SELECT * from
    2 (select ename, join_date from test222
    3 order by join_date desc)
    4 WHERE rownum < 6
    5 /
    ENAME JOIN_DATE
    II61111208401 19-MAR-02
    II61451208038 18-MAR-02
    PI20014184983 01-MAR-02
    BNF2221148037C 28-FEB-02
    UO78902581 18-FEB-02
    Can you see the problem now ?
    You can test this concept with your own table.
    have a good day,
    Sri

  • Best way to find the count of rows affected by a query

    Hi All,
    Is there a way to find the row count without actually executing the SQL statement? The count need not be accurate but it should be within acceptable limits. I know we can use 'explain plan' for this. But the value in plan_table.cardinality is way out of the actual expected count.
    We would appreciate any pointers and/or suggestions.
    Thanks
    Edited by: user779842 on May 4, 2011 2:21 AM

    maybe you can try this
    How to get estimated number of rows of query without running actual query :
    CREATE OR REPLACE FUNCTION get_rows_number (sql_select VARCHAR2, sql_id VARCHAR2) RETURN NUMBER AS
    rows_number NUMBER;
    BEGIN
    EXECUTE IMMEDIATE
    ‘EXPLAIN PLAN SET STATEMENT_ID = ‘||CHR(39) || sql_id || CHR(39)||’ FOR ‘ || sql_select;
    SELECT t.cardinality
    INTO rows_number
    FROM plan_table T
    WHERE statement_id = sql_id AND ID = 0;
    RETURN rows_number;
    END;hope it helps!

  • How to get count of last 30 days and total of count of rows in a single query

    Hi All,
    My requirement is to write a sql query with the following requirement
    I have a table TEST which has 6500 rows out of which the created date > 30 which means records from last 30 days are like 60.So if i write a query like this 
    Select Count(*) from TEST where CreatedDdate > 30
    This one would give me last 30 days count but in the same query i also want the count(*) which would be 6500
    So my output should be one row with 6500 in one column and 65 in second column
    Can someone please help me on how to do this?
    If you have any questions or if i am unclear please let me know.
    Thanks

    declare @sdate table(sdate date)
    insert into @sdate
    values('20150418'),('20140418')
    Select Count(*) as [total],count(case when(datediff(day,sdate,getdate()))<30 then 1 else null end) as [Last30days] from @sdate
    Hope it Helps!!

  • SQL-display two rows in a table as one row in the select query

    Hi guys
    Sorry if this sounds a little odd.
    I have two tables
    Im sorry but i tried to format these tables in text to make them look like tables but this text processor deletes space based formatting.
    States
    state id | Name
    1 | california
    2 | New york
    3 | New hampshire
    .......so on
    Grades
    Gradeid | State id | Language | Avgscore |
    1 | 1 | ENG | 67 |
    2 | 1 | FRENCH | 76 |
    2 | 2 | SPANISH | 34 |
    Now i wanna write an sql query thats gonna display like
    State Name | State id | English | French | SPANISH|
    California | 1 | 67 | 76 | null
    New York | 2 | null | null | 34
    I know how to get just an sql query where i can say
    SELECT A.id, A.Name, G.Language,G.Avgscore
    FROM States A , Grades G
    where A.state_id = G.state_id
    and G.Language = 'English'
    How do i accomplish this?
    Thanks
    J
    Edited by: user7348303 on Apr 1, 2010 1:15 PM

    Regarding:
    Im sorry but i tried to format these tables in text to make them look like tables but this text processor deletes space based formatting.Use this tag: {noformat}{noformat}
    before and after your example, so formatting will be maintained when posting your example.
    Example, when you type:
    {noformat}select * from dual;
    {noformat}
    it will appear as:select * from dual;
    when you post it on the forum.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to find out which sub query returns more than one row

    Hi all,
    Can any one give me clue ,how to find out which sub query returns more than one row in the following query .
    /* Formatted on 2011/05/17 19:22 (Formatter Plus v4.8.8) */
    SELECT a.*, ROWNUM AS rnm
      FROM (SELECT DISTINCT '1' AS "Page View", ou.org_unit_name AS "Org",
                            prxm.mbr_idntfr AS "Beneficiary ID",
                               md.last_name
                            || ', '
                            || md.first_name AS "Beneficiary Name",
                            pci.idntfr AS "Tracking No.",
                            TO_CHAR (TRUNC (req.pa_rqst_date),
                                     'MM/dd/yyyy'
                                    ) AS "Request Date",
                            sts.status_name AS "Status",
                            req.pa_rqst_sid AS "Request #",
                            prxm.mbr_sid AS "Mbr_sid",
                            TO_CHAR
                                  (TRUNC (req.pa_revision_date),
                                   'MM/dd/yyyy'
                                  ) AS "Last Updated",
                            TO_CHAR (psd.TO_DATE, 'MM/dd/yyyy') AS "TO_DATE",
                            prxpl.prvdr_lctn_iid AS "PRVDR_LCTN_IID",
                            pd.prvdr_sid AS "PRVDR_SID", 'Y' AS "State View",
                            DECODE
                               ((SELECT DISTINCT pd.national_prvdr_idntfr
                                            FROM pa_request_x_provider_location prxplo
                                           WHERE prxplo.pa_rqst_sid =
                                                                   req.pa_rqst_sid
                                             AND prxplo.oprtnl_flag = 'A'
                                             AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
                                0, (SELECT prxplo.prvdr_lctn_idntfr
                                      FROM pa_request_x_provider_location prxplo
                                     WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
                                       AND prxplo.oprtnl_flag = 'A'
                                       AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
                                NULL, (SELECT prxplo.prvdr_lctn_idntfr
                                         FROM pa_request_x_provider_location prxplo
                                        WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
                                          AND prxplo.oprtnl_flag = 'A'
                                          AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
                                (SELECT DISTINCT pd.national_prvdr_idntfr
                                            FROM pa_request_x_provider_location prxplo
                                           WHERE prxplo.pa_rqst_sid =
                                                                   req.pa_rqst_sid
                                             AND prxplo.oprtnl_flag = 'A'
                                             AND prxplo.pa_prvdr_type_lkpcd = 'RR')
                               ) AS "NPI/ID",
                            DECODE
                               ((SELECT pd.org_bsns_name
                                   FROM pa_request_x_provider_location prxplo
                                  WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
                                    AND prxplo.oprtnl_flag = 'A'
                                    AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
                                NULL, (SELECT    pd.last_name
                                              || ', '
                                              || pd.first_name
                                              || ' '
                                              || pd.middle_name
                                         FROM pa_request_x_provider_location prxplo
                                        WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
                                          AND prxplo.oprtnl_flag = 'A'
                                          AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
                                (SELECT pd.org_bsns_name
                                   FROM pa_request_x_provider_location prxplo
                                  WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
                                    AND prxplo.oprtnl_flag = 'A'
                                    AND prxplo.pa_prvdr_type_lkpcd = 'RR')
                               ) AS "Prvdr Name",
                            TO_CHAR (psd.from_date,
                                     'MM/dd/yyyy'
                                    ) AS "Srvc From Date",
                            TO_CHAR (req.validity_start_date,
                                     'MM/DD/YYYY'
                                    ) AS "Due Date",
                            (fn_get_busniess_days (TRUNC (req.validity_start_date))
                            ) AS "Days<br>Left",
                            req.pa_mode_type_lkpcd AS "Source",
                            TO_CHAR (TRUNC (wmdtl.rtng_date),
                                     'MM/dd/yyyy'
                                    ) AS "Assigned On",
                            NVL (wmdtl.assigned_to_user_name,
                                 'Not Assigned'
                                ) AS "Assigned To",
                            req.org_unit_sid AS "OrgUnitSid",
                            TO_CHAR
                                 (wmdtl.modified_date,
                                  'MM/dd/yyyy hh24:mi:ss'
                                 ) AS "WTRD_MODIFIED_DATE",
                            TO_CHAR (wmdtl.rtng_date,
                                     'MM/dd/yyyy'
                                    ) AS "WTRD_RTNG_DATE",
                            req.status_cid AS "PA_STATUS_CID",
                            TO_CHAR (req.modified_date,
                                     'MM/dd/yyyy'
                                    ) AS "PA_REQ_MODIFIED_DATE",
                            prs.state_pa_srvc_type_code
                                                     AS "STATE_PA_SRVC_TYPE_CODE",
                            wmdtl.wm_pa_task_rtng_dtl_sid
                                                        AS "WM_TASK_RTNG_DTL_SID",
                            wmdtl.assigned_to_user_acct_sid
                                              AS "WTRD_Assigned_to_user_acct_sid",
                            (fn_get_busniess_days (TRUNC (req.validity_start_date))
                            ) AS "Days<br>LeftSort",
                            wmdtl.assigned_to_org_unit_sid
                                                  AS "WTRD_Assigned_to_OrgUntSid",
                            DECODE
                               ((SELECT COUNT (*)
                                   FROM pa_request_status prs
                                  WHERE prs.pa_rqst_sid = req.pa_rqst_sid
                                    AND prs.status_cid = 5
                                    AND prs.oprtnl_flag = 'I'),
                                0, 'N',
                                'Y'
                               ) AS "SHOW_UTILIZATION"
                       FROM   pa_request req,
                             pa_certification_identifier pci,
                             status sts,
                             pa_request_x_member prxm,
                             wm_pa_task_routing_detail wmdtl,
                             pa_service_date psd,
                             org_unit ou,
                             pa_request_service prs,
                             pa_request_x_provider_location prxpl,
                             provider_location pl,
                             provider_detail pd,
                             provider p,
                             mbr_dmgrphc md
                      WHERE req.oprtnl_flag = 'A'
                        AND req.status_cid NOT IN
                                     (20, 30, 70, 25, 80, 96, 85, 5, 97, 98, 101)
                        AND req.org_unit_sid IN
                               (3057, 3142, 3058, 3143, 3059, 3144, 3060, 3145,
                                3061, 3146, 3062, 3147, 3063, 3148, 3064, 3149,
                                3065, 3150, 3066, 3151, 3067, 3152, 3068, 3153,
                                3069, 3154, 3070, 3155, 3071, 3156, 3072, 3157,
                                3073, 3158, 3074, 3159, 3075, 3160, 3076, 3161,
                                3077, 3162, 3078, 3163, 3079, 3164, 3080, 3165,
                                3081, 3166, 3082, 3167, 3083, 3168, 3084, 3169,
                                3085, 3170, 3086, 3171, 3087, 3172, 3088, 3173,
                                3089, 3174, 3090, 3175, 3091, 3176, 3092, 3177,
                                3093, 3178, 3094, 3179, 3095, 3180, 3096, 3181,
                                3097, 3182, 3098, 3183, 3099, 3184, 3100, 3185,
                                3101, 3186, 3102, 3187, 3103, 3003, 75000104,
                                75000108, 2006, 75000103, 75000102, 75000113,
                                75000111, 75000109, 2001, 2009, 75000105,
                                75000107, 2004, 2010, 2013, 2014, 2005, 2011,
                                75000112, 2002, 1001, 2012, 75000106, 2007,
                                75000101, 2003, 75000110, 2008, 3001, 3002, 3019,
                                3104, 3020, 3105, 3021, 3106, 3022, 3107, 3023,
                                3108, 3024, 3109, 3025, 3110, 3026, 3111, 3027,
                                3112, 3028, 3113, 3029, 3114, 3030, 3115, 3031,
                                3116, 3032, 3117, 3033, 3118, 3034, 3119, 3035,
                                3120, 3036, 3121, 3037, 3122, 3038, 3123, 3039,
                                3124, 3040, 3125, 3041, 3126, 3042, 3127, 3043,
                                3128, 3044, 3129, 3045, 3130, 3046, 3131, 3047,
                                3132, 3048, 3133, 3049, 3134, 3050, 3135, 3051,
                                3136, 3052, 3137, 3053, 3138, 3054, 3139, 3055,
                                3140, 3056, 3141)
                        AND req.pa_rqst_sid = prs.pa_rqst_sid
                        AND prs.oprtnl_flag = 'A'
                        AND prs.pa_rqst_srvc_sid = psd.pa_rqst_srvc_sid
                        AND psd.oprtnl_flag = 'A'
                        AND req.pa_rqst_sid = pci.pa_rqst_sid
                        AND pci.oprtnl_flag = 'A'
                        AND req.pa_rqst_sid = prxm.pa_rqst_sid
                        AND prxm.oprtnl_flag = 'A'
                        AND md.oprtnl_flag = 'A'
                        AND md.status_cid = 2
                        AND TRUNC (SYSDATE) BETWEEN md.from_date AND md.TO_DATE
                        AND prxm.mbr_sid = md.mbr_sid
                        AND ou.org_unit_sid = req.org_unit_sid
                        AND ou.oprtnl_flag = 'A'
                        AND req.pa_rqst_sid = prxpl.pa_rqst_sid
                        AND prxm.pa_rqst_sid = prxpl.pa_rqst_sid
                        AND pci.pa_rqst_sid = prxm.pa_rqst_sid
                        AND pci.pa_rqst_sid = wmdtl.subsystem_task_sid
                        AND pci.pa_rqst_sid = prxpl.pa_rqst_sid
                        AND prxpl.pa_prvdr_type_lkpcd = 'RR'
                        AND prxpl.oprtnl_flag = 'A'
                        AND req.status_cid = sts.status_cid
                        AND sts.status_type_cid = 3
                        AND sts.oprtnl_flag = 'A'
                        AND prxpl.prvdr_lctn_iid = pl.prvdr_lctn_iid
                        AND p.prvdr_sid = pd.prvdr_sid
                        AND p.prvdr_sid = pl.prvdr_sid
                        AND pd.oprtnl_flag = 'A'
                        AND pd.status_cid = 2
                        AND TRUNC (SYSDATE) BETWEEN pd.from_date AND pd.TO_DATE
                        AND wmdtl.subsystem_task_sid = req.pa_rqst_sid
                        AND wmdtl.subsystem_lkpcd = 'PA'
                        AND wmdtl.oprtnl_flag = 'A'
                        AND req.pa_rqst_date > (SYSDATE - 365)
                                       ORDER BY TO_DATE ("Request Date", 'MM/dd/yyyy hh24:mi:ss') DESC,
                            "Beneficiary Name" ASC) a
    WHERE ROWNUM < 102;regards,
    P Prakash
    Edited by: BluShadow on 17-May-2011 15:01
    added {noformat}{noformat} tags around the code                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    833560 wrote:
    Can any one give me clue ,how to find out which sub query returns more than one row in the following query .This is why smaller, simpler queries are easier to work with than huge ones - when something like this goes wrong smaller queries are much eaiser to debug. Unfortunately using smaller, easier-to-work with queries is not always an option
    Ganesh is right - you will have to dissect the big query bit by bit until you find the offending subquery. If there is another way I would like to find out about it too.
    The easiest way to do this is probably to use block comments to isolate parts of the query bit by bit until you find the offending part. If you carefully examine the subqueries you might be able to figure out which one is returning multiple rows without commenting everything
    Good luck!

  • Counting rows in a mysql query

    Hey
    How do i count the rows in a mysql query?
    I have tried to make a while loop (as you can see in the code), but if i make this while loop i cant use the same query to get the database data.
    Doesnt java have a function that counts the rows?
    public DefaultTableModel searchCategory(String searchString){
            String returnString = "";
            try{
                RS = connection.executeQuery("SELECT name, price, products_type_id FROM katrinelund_products WHERE products_type_id = (SELECT products_type_id FROM katrinelund_products_type WHERE name LIKE '%"+searchString+"%')");
                int rowCount = 0;
                while(RS.next()){
                    rowCount++;
                String[] columnNames = {"Navn", "Pris", "Produkt type"};
                Object[][] data = new Object[rowCount][columnNames.length];
                int i=0;
                while(RS.next()){
                    data[0] = RS.getString(1);
    data[i][1] = RS.getString(2);
    data[i][2] = RS.getString(3);
    i++;
    table = new DefaultTableModel(data, columnNames);
    catch(SQLException E){
    System.out.println("Der skete en fejl" + E.getMessage());
    return table;
    }NOTE: the connection to the database is stored in the connection variable.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    yawmark wrote:
    The SELECT COUNT(*) cannot be fetched among other data, so in this case you must send two queries. Then there is much simplier to use the method I mentioned above.While it may be "simpler", it's not supported in a non-trivial number of drivers. So there are a number of situations in which your "simple" solution will not work. I assume you've been fortunate enough to work only with drivers that do support the functionality you recommend, but I can also only assume that you haven't had much experience beyond that.I apologize for my spelling errors. I'm not a native englishman.
    yawmark wrote:
    Knowing the amount of rows a resultset returns can be interesting if you're making some kind of search engine. Knowing the amount of data returned for a particular query can certainly be useful, and we've presented some reasonable means of obtaining that kind of information that don't rely on potentially unsupported features.
    I don't now about unsupported features. The ResultSet is (as far as I know) not tied to a specific SQL database. This, and all of it's methods is in the java.sql.ResultSet interface. Then all classes implementing this must have these methods. Am I not right?
    yawmark wrote:
    Stop dealing with however it's necessary or not.Sorry, partner, but you don't get to decide what I post here.
    This guy wants this problem to be solved, so apparentley he has a usage for it...And what you're apparently failing notice is that there are other solutions (better, in many cases) than the solution which you posted. Don't make the mistake of thinking your suggestion is golden. It isn't. Besides, there are no shortage of beginners that want the "problem" of i = i++ to be "solved"; no doubt they think they have an apparent usage for it, too. ~I'm well aware of that you decide on your own what to post. I just don't see how it is necessary to discuss the matter of necessity in this case. The problem still remains.
    I don't want any fuss here. I'm just so sick of everyone who yells "you don't need to know that". I haven't decried any of the other solutions (at least it wasn't my point), all I said was that it's not a good idea to send multiple queries to the database when you already have the answer three rows of code away. In some rare situations, the data may have been changed during the short period of time as the database is finished with the first query before you send the next one.

  • Paging and count of rows

    Hi,
    I have a procedure doing paging and returning the count of rows:
    As you see I used 2 select, one for paging and one for getting total row counts.
    Is there a way to get rid of "SELECT count(*) into PO_TOTAL FROM TABLE1;"?
    CREATE OR REPLACE PACKAGE BODY MYPACKAGE AS
    TYPE T_CURSOR IS REF CURSOR;
    PROCEDURE SP_PAGING
    PI_STARTID IN NUMBER,
    PI_ENDID IN NUMBER,
    PO_TOTAL OUT NUMBER,
    CUR_OUT OUT T_CURSOR
    IS
    BEGIN
    OPEN CUR_OUT FOR
    SELECT *
    FROM (SELECT row_.*, ROWNUM rownum_
    FROM (
    SELECT column1, column2, column3 FROM TABLE1
    ) row_
    WHERE ROWNUM <= PI_ENDID)
    WHERE rownum_ >= PI_STARTID;
    SELECT count(*) into PO_TOTAL FROM TABLE1;
    END SP_PAGING;
    END MYPACKAGE;

    Yes, I can reproduce that:
    SQL> create table emp1 as select * from emp
      2  /
    Table created.
    SQL> exec dbms_stats.gather_table_stats('SCOTT','EMP1');
    PL/SQL procedure successfully completed.
    SQL> EXPLAIN PLAN FOR
      2  SELECT  ename,
      3          job,
      4          sal,
      5          cnt
      6    FROM  (
      7           SELECT  ename,
      8                   job,
      9                   sal,
    10                   count(*) over() cnt,
    11                   row_number() over(order by 1) rn
    12             FROM  emp1
    13          )
    14    WHERE rn BETWEEN 4 AND 9;
    Explained.
    SQL> @?\rdbms\admin\utlxpls
    PLAN_TABLE_OUTPUT
    Plan hash value: 1444408506
    | Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |      |    14 |   728 |     4  (25)| 00:00:01 |
    |*  1 |  VIEW               |      |    14 |   728 |     4  (25)| 00:00:01 |
    |   2 |   WINDOW BUFFER     |      |    14 |   252 |     4  (25)| 00:00:01 |
    |   3 |    TABLE ACCESS FULL| EMP1 |    14 |   252 |     3   (0)| 00:00:01 |
    PLAN_TABLE_OUTPUT
    Predicate Information (identified by operation id):
       1 - filter("RN">=4 AND "RN"<=9)
    15 rows selected.
    SQL> EXPLAIN PLAN FOR
      2  SELECT *
      3  FROM (SELECT row_.*, ROWNUM rownum_
      4  FROM (
      5  SELECT ename,job,sal, count(*) over() FROM emp1
      6  ) row_
      7  WHERE ROWNUM <= 9)
      8  WHERE rownum_ >= 4;
    Explained.
    SQL> @?\rdbms\admin\utlxpls
    PLAN_TABLE_OUTPUT
    Plan hash value: 519025698
    | Id  | Operation             | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT      |      |     9 |   468 |     2   (0)| 00:00:01 |
    |*  1 |  VIEW                 |      |     9 |   468 |     2   (0)| 00:00:01 |
    |*  2 |   COUNT STOPKEY       |      |       |       |            |          |
    |   3 |    VIEW               |      |     9 |   351 |     2   (0)| 00:00:01 |
    |   4 |     WINDOW BUFFER     |      |     9 |   162 |     2   (0)| 00:00:01 |
    |   5 |      TABLE ACCESS FULL| EMP1 |     9 |   162 |     2   (0)| 00:00:01 |
    PLAN_TABLE_OUTPUT
    Predicate Information (identified by operation id):
       1 - filter("ROWNUM_">=4)
       2 - filter(ROWNUM<=9)
    18 rows selected.
    SQL> However, you interpreted it incorrectly. Your query will still fetch all rows in TABLE1. Optimizer is smart enough to stop creating window buffer after 9 rows and that is what you see 9 in explain plan, while my query builds 14 row window buffer and then filters. So your query will be a bit faster.
    SY.
    Edited by: Solomon Yakobson on Jan 25, 2009 2:51 PM

  • Still problem with single-row subquery returns more than one row

    //i did join each table but query runs forever and fail. looks Cartesian join so comes up the following SQL
    the following query has a problem. would you please help me, please
    Select pe.expense_id
    ,PE.CODE
    ,PE.PROJECT_ID
    ,PE.LDATE
    ,PE.INAMOUNT pe_amount
    ,(SELECT TRX.INV_AMOUNT FROM TRXEXPENSES TRX
    WHERE PE.EXPENSE_ID=TRX.EXPENSE_ID) AS invamount
    ,(SELECT RE.AMOUNT FROM REEXPENSES RE WHERE
    PE.EXPENSE_ID=RE.EXPENSE_ID) AS recogamount
    ,(SELECT MLE.M_AMOUNT FROM MATEXPENSES MLE
    WHERE PE.EXPENSE_ID=MLE.EXPENSE_ID) AS matamount
    from EXPENSES PE
    where pe.expense_id=5600
    group by expense_id,CODE,PROJECT_ID,LDATE,inamount
    //get error message
    ora-01427:single-row subquery returns more than one row
    //check database
    select expense_id,count(*) from TRXEXPENSES
    where expense_id in(select expense_id from
    expenses)
    group by expense_id
    having count(*)>1
    //here is duplicate record a lot
    EXPENSE_ID     COUNT(*)
    4176     2
    5600     3
    9572     2
    9573     2
    9574     2

    Yes, Expense_id has so many returning rows for trx.inv_amount from trxexpenses in subquery.
    I want to show Expense_id with retruning rows using the above query.
    ex)The result of the query is like that;
    Expense_ Id project_id Ldate InvAmount RecogAmount MatAmount
    5600 123 3/2/02 $100(InvAmount)
    5600 432 3/12/02 $200(recogAmount)
    5600 432 4/12/02 $250(MatAmount)
    Thank you so much
    Message was edited by:
    user524064
    Message was edited by:
    user524064

  • What does it mean when the usecounts of Parse Tree for a view is incrementing when a select query is issued against the view?

    I'm using SQL Server 2008 R2 (10.50.4033) and I'm troubleshooting an issue that a select query against a specific view is taking more than 30 seconds consistently.   The issue just starts happening this week and there is no mass changes in data.  
    The problem only occur if the query is issued from an IIS application but not from SSMS.  One thing I noticed is that sys.dm_exec_cached_plans is returning 2 Parse Tree rows for the view -  one created when the select query is issued
    1st time from the IIS application and another one created when the same select query is issued 1st time from SSMS.   The usecounts of the Parse Tree row for the view (the IIS one) is increasing whenever the select query is issued.  The
    usecounts of the Parse Tree row for the view (the SSMS one) does not increase when the select query is issued again. 
    There seems to be a correlation between the slowness of the query and the increasing of the usecounts of the Parse Tree row for the view.  
    I don't know why there is 2 Parse Tree rows for the view.  There is also 2 Compiled Plan rows for the select query.  
    What does the Parse Tree row mean especially the usecounts column?

    >> The issue just starts happening this week and there is no mass changes in data.  
    There might be a mass changes in the execution plan for several reason without mass changes in data
    If you have the old version and a way to check the old execution plan, and compare to the new one, that this should be your starting point. In most cases you don't have this option and we need to monitor from scratch.
    >> The problem only occur if the query is issued from an IIS application but not from SSMS.
    This mean that we know exactly what is the different and you can compare both execution plan. once you do it, you will find that they are no the same. But this is very common issue and we can know that it is a result of different SETting while connecting
    from different application. SSMS is an external app like any app that you develop in Visual studio but the SSMS dose not use the Dot.Net default options.
    Please check this link, to find the full explanation and solutions:
    http://www.sommarskog.se/query-plan-mysteries.html
    Take a look at sys.dm_exec_sessions for your ASP.Net application and for your SSMS session.
    If you need more specific help, then we need more information and less stories :-)
    We need to see the DDL+DML+Query and both execution plans
    >> What does the Parse Tree row mean
    I am not sure what you mean but the parse tree represents the logical steps necessary to execute the query that has been requested. you can check this tutorial about the execution plan: https://www.simple-talk.com/sql/performance/execution-plan-basics/ or
    this one: http://www.developer.com/db/understanding-a-sql-server-query-execution-plan.html
    >> regarding the usecount column or any other column check this link:
    https://msdn.microsoft.com/en-us/library/ms187404.aspx?f=255&MSPPError=-2147217396.
      Ronen Ariely
     [Personal Site]    [Blog]    [Facebook]

  • How will get subquery return multiple values and passing to the main query

    Hi all ;
    here i given one sql query
    1)select decode(a.FLG,'Y','yes','N','no','null')||'] '||a.p_type||' : '|| initcap(replace(substr(b.mgr,0,instr(b.mgr,'@')-1),'.',' '))||' - '||
    b.name||' ('|| substr(a.name,0,instr(a.name,'-')-1)||')'
    from table1 a
    join table3 c on c.emptype = a.emptype
    left outer join table2 b on a.name = b.name
    where a.mgrid = 100;
    if i run this above query returning multiple values depend on sa.mgr values.
    like output coming like this
    [yes]:2000-anbarasan
    [yes]:2700-anb
    [yes]:2000-rasan
    [yes]:2807-anbarasan
    [yes]:2700-anbanu
    [yes]:2000-null
    2) this sub query i am passing with main query
    select sa.mgrid,sa.sal,(select decode(a.FLG,'Y','yes','N','no','null')||'] '||a.p_type||' : '||
    initcap(replace(substr(b.mgr,0,instr(b.mgr,'@')-1),'.',' '))||' - '||
    b .name||' ('|| substr(a.name,0,instr(a.name,'-')-1)||')'
    from table1 a
    join table3 c on c.emptype = a.emptype
    left outer join table2 b on a.name = b.name
    where a.mgrid = 100)" test " from table4 sa,table5 te ,table6 ft where sa.id(+)=te.id and sa.mgr=ft.mgr;
    my final out put required like this:
    mgrid sal test
    100 20000 [yes]:2000-anbarasan
    [yes]:2700-anb
    [yes]:2000-rasan
    [yes]:2807-anbarasan
    [yes]:2700-anbanu
    [yes]:2000-null
    but i am getting erro:
    1)missing paranths-it solved
    2)single row subquery return more then one row.
    give me the correct solution.how will solve this problem
    Edited by: anbarasan on Sep 29, 2008 6:49 AM
    Edited by: anbarasan on Sep 29, 2008 6:51 AM
    Edited by: anbarasan on Sep 29, 2008 6:53 AM
    Edited by: anbarasan on Sep 29, 2008 6:56 AM
    Edited by: anbarasan on Sep 29, 2008 6:58 AM

    Hi,
    It doesn't look like you posted either the complete query or the complete error message (including line number). Try again.
    "single row subquery return more then one row" usually means you are using a sub-query in a place where a single expression is expected, for example the column called avg_sal in this query:
    SELECT  ename
    ,       sal
    ,       (SELECT  AVG (sal) FROM scott.dept WHERE deptno = e.deptno) AS avg_sal  -- Scalar-sub-query
    FROM    scott.emp  e; The error occurs when the sub-query returns more than one row
    If the sub-querry really is supoosed to be returning only one row, the solution is to fix the sub-query, usually be adding something to the WHERE clause.
    If the sub-query is supposed to return more than one row, then the main query has to be re-written, perhaps as a join.
    Post a little sample data and the results you want from that data if you need help.

Maybe you are looking for

  • Problem with a view in XK01 transaction

    Hi All, I am working on upload conversion for Vendor Master. While doing conversion, i am getting a problem with a Contact person view in XK01 transaction. In contact person view the telephone field column sometimes allowing to add data ,sometimes it

  • 8.3 filenames on classpath under Windows XP

    Hi, I have an application where the classpath may include paths with unicode characters. Since there is no obvious way to pass such paths to the JVM at startup, I have tried to convert the paths to the short (8.3) format prior to passing them to the

  • Web Service Data Control vs Web Service Proxy

    Hi, I am using Jdev 11.1.1.4 and ADF BC and ADF Faces. I want to invoke bpel web service from my application. Which one would the the better appraoch data control or proxy? In which scenario we should go for web service data control? ~Abhijit

  • Consuming messages using Java

    Hi, I am using BlazeDS running in Tomcat 6.0.16. The Flex client components are written using Flex 3. I have a messaging destination set up and the Flex producers and consumers are working fine. I am able to push messages from the server top the clie

  • Pavilion HPE h8-1214 windows 7 Bluetooth

    I am having problems with my bluetooth driver, for some reason none of my bluetooth devices can connect to my computer, and I found a page where I can redownload my bluetooth drivers.. but it only works with WIN 8, and I have a Win 7 64bit computer.