Group by Vs Partition By Clause

Hello,
Can you please help me in resolving the below issue,
I have explained the scenario below with dummy table,
CREATE TABLE emp (empno NUMBER(12), ename VARCHAR2(10), deptno NUMBER(12));
INSERT INTO emp
(empno, ename, deptno
VALUES (1, 'A', 10
INSERT INTO emp
(empno, ename, deptno
VALUES (2, 'B', 10
INSERT INTO emp
(empno, ename, deptno
VALUES (3, 'C', 20
INSERT INTO emp
(empno, ename, deptno
VALUES (4, 'D', 20
INSERT INTO emp
(empno, ename, deptno
VALUES (5, 'E', 30
COMMIT ;
SELECT DISTINCT deptno, SUM (empno) / SUM (empno) OVER (PARTITION BY deptno)
FROM emp
GROUP BY deptno;
ORA-00979: not a GROUP BY expression
Earlier i had the query like
SELECT DISTINCT deptno, SUM (empno) OVER (PARTITION BY deptno,empno) / SUM (empno) OVER (PARTITION BY deptno)
FROM emp;
which executed successfully with wrong result.
Please guide me how to resolve this issue,
Thanks,
Santhosh

Hi,
santhosh.shivaram wrote:
Hello all, sorry for the providing the limited data, I have now depicting the actual data set and the current select query which is giving error and desired output. Please let me know if you need further information on this.
/* Formatted on 2012/09/14 08:00 (Formatter Plus v4.8.8) */ ...If you're going to the trouble of formatting the data, post it inside \ tags, so that this site won't remove the formatting.  See the forum FAQ {message:id=9360002}
**Current query:**
SELECT rep_date, cnty, loc, component_code,
SUM (volume) / SUM (volume) OVER (PARTITION BY rep_date, cnty, loc)This is the same problem you had before, and was explained in the first answer {message:id=10573091}  Don't you read the replies you get?SUM (volume) OVER (PARTITION BY rep_date, cnty, loc)
can't be used in this GROUP BY query, because it depends on volume, and volume isn't one of the GROUP BY expressions.
FROM table1
GROUP BY rep_date, cnty, loc, component_code;
when execute this query i am getting "ORA-00979: not a GROUP BY expression" error
My desired output_Formatting is especially important for the output.  Which do you think is easier to read and understand: what you posted:
Rep_Date     Cnty     Loc     Component_Code     QTY_VOL
9/12/2012     2     1     CONTRACT      -0.019000516
9/12/2012     2     1     CONTRACT      -0.019000516
9/12/2012     2     1     NON-CONTRACT      -0.893525112
9/12/2012     2     1     NON-CONTRACT      -0.89322
9/12/2012     2     1     CONTRACT-INDEX     1.912525629
9/12/2012     2     1     CONTRACT-INDEX     1.912526
9/12/2012     2     1     CONTRACT-INDEX     1.912526
9/12/2012     2     4     CONTRACT     0.015197825
9/12/2012     2     4     CONTRACT     0.015198
9/12/2012     2     4     NON-CONTRACT     0.984802175
9/12/2012     2     4     NON-CONTRACT     0.984802or this?Rep_Date     Cnty     Loc     Component_Code     QTY_VOL
9/12/2012     2     1     CONTRACT -0.019000516
9/12/2012     2     1     CONTRACT -0.019000516
9/12/2012     2     1     NON-CONTRACT      -0.893525112
9/12/2012     2     1     NON-CONTRACT      -0.89322
9/12/2012     2     1     CONTRACT-INDEX     1.912525629
9/12/2012     2     1     CONTRACT-INDEX     1.912526
9/12/2012     2     1     CONTRACT-INDEX     1.912526
9/12/2012     2     4     CONTRACT     0.015197825
9/12/2012     2     4     CONTRACT     0.015198
9/12/2012     2     4     NON-CONTRACT     0.984802175
9/12/2012     2     4     NON-CONTRACT     0.984802
Which do you think will lead to more answers?  Quicker answers?  Better answers?
Please let me know if you need any more information.Explain the results.
How do you compute the qty_vol column?  Give a couple of very specific examples, showing step by step how you calculate the values given from the sample data.
What does each row of the output represent? Your query says
GROUP BY rep_date, cnty, loc, component_code;which means the result set will have 1 row for each distinct combiation of rep_date, cnty, loc and component_code, but your desired output has at least 2 rows for every distinct combination of them, and in one case you want 3 rows with the same rep_date, cnty, loc and component_code.  How do you decide when you want 2 rows, and when you need 3?  Will there be occassions when you need 4 row, or 5, or 1?
All the rows with the same rep_date, cnty, loc and component_code have *nearly* the same qty_vol, but usually not quite the same.  Sometimes qty_col is rounded: sometimes it's changed slightly, but not just rounded (-0.893525112 get converted to -0.89322).  How do you decide when it's rounded, when it remains the same, and when it's changed to a completely different number?  When it's rounded, how do you decide how many digits to round it to?
Edited by: Frank Kulash on Sep 14, 2012 12:44 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • How to group the values with this partition over clause ?

    Hi,
    I have a nice request :
    select  c.libelle "Activité", sum(b.duree) "Durée"
    from    fiche a, activite_faite b,
            activites c, agent d
    where   a.date_activite
    BETWEEN TO_DATE('20/09/2009', 'DD/MM/YYYY') AND TO_DATE('26/10/2009', 'DD/MM/YYYY')
    AND     a.agent_id = 104
    AND     a.fiche_id = b.fiche_id
    AND     b.activites_id = c.activites_id
    AND     a.agent_id = d.agent_id
    group   by c.libelle
    order   by sum(b.duree)It gives me this nice result :
    ACTIVITE  DUREE
         Tonte            27I want to get a percentage, i use ratio_to_report
    select  a.fiche_id, c.libelle "Activité", ratio_to_report(duree) over (partition by c.activites_id) * 100 "Durée"
    from    fiche a, activite_faite b,
            activites c, agent d
    where   a.date_activite
    BETWEEN TO_DATE('20/09/2009', 'DD/MM/YYYY') AND TO_DATE('26/10/2009', 'DD/MM/YYYY')
    AND     a.agent_id = 104
    AND     a.fiche_id = b.fiche_id
    AND     b.activites_id = c.activites_id
    AND     a.agent_id = d.agent_idIt gives me this less nice result :
    Tonte 7,40740740740740740740740740740740740741
    Tonte 33,33333333333333333333333333333333333333
    Tonte 33,33333333333333333333333333333333333333
    Tonte 25,92592592592592592592592592592592592593I would like to get this result :
    Tonte 100I tried "grouping" values in the partition over clause but without success.
    Any help appreciated from the slq-masters :
    Regards,
    Christian

    Christian from France wrote:
    I would like to get this result :
    Tonte 100
    Hi,
    Why not this
    select  c.libelle "Activité", 100 "Durée"
    from    fiche a, activite_faite b,
            activites c, agent d
    where   a.date_activite
    BETWEEN TO_DATE('20/09/2009', 'DD/MM/YYYY') AND TO_DATE('26/10/2009', 'DD/MM/YYYY')
    AND     a.agent_id = 104
    AND     a.fiche_id = b.fiche_id
    AND     b.activites_id = c.activites_id
    AND     a.agent_id = d.agent_id
    group   by c.libelle
    order   by sum(b.duree)Because it would always be 100 (if you are taking as percentage) be what ever the count of duree be.
    Or did I miss something in understanding the requirement.
    Regards
    Anurag

  • Group by vs partition by

    Hi,
    I am new to my project where I need some help.
    My requirement is like below
    In EMP table I need to group the all the employees who belongs to one department, I  used group by function to fetch the results, but my lead asked me to use partition by clause. So I am not sure is I get different result set by using partition by ?
    If yes How can I use it.
    Thanks,

    grouping reduces the number of result rows - and analytics do not. Here is a small emp example:
    select ENAME
         , job
         , count(*) over (partition by job) job_count
      from emp
    order by ename;
    ENAME      JOB        JOB_COUNT
    ADAMS      CLERK              4
    ALLEN      SALESMAN           4
    BLAKE      MANAGER            3
    CLARK      MANAGER            3
    FORD       ANALYST            2
    JAMES      CLERK              4
    JONES      MANAGER            3
    KING       PRESIDENT          1
    MARTIN     SALESMAN           4
    MILLER     CLERK              4
    SCOTT      ANALYST            2
    SMITH      CLERK              4
    TURNER     SALESMAN           4
    WARD       SALESMAN           4
    With group by you would only get one line per job group. You could get the same result with a self join with a grouped result:
    select e1.ename
         , e1.job
         , e2.job_count
      from emp e1
         , (select JOB
                 , count(*) job_count
              from emp
             group by job) e2
    where e1.job = e2.job
    order by e1.ename;
    ENAME      JOB        JOB_COUNT
    ADAMS      CLERK              4
    ALLEN      SALESMAN           4
    BLAKE      MANAGER            3
    CLARK      MANAGER            3
    FORD       ANALYST            2
    JAMES      CLERK              4
    JONES      MANAGER            3
    KING       PRESIDENT          1
    MARTIN     SALESMAN           4
    MILLER     CLERK              4
    SCOTT      ANALYST            2
    SMITH      CLERK              4
    TURNER     SALESMAN           4
    WARD       SALESMAN           4

  • Missing partition by clause causing wrong aggregation

    Hello all!
    I have a Location Hierarchy. Country Region > Country > State > City
    When I create a report using Country, Headcount ( Month = July 11) I get correct results with right aggregation:
    United States      2000           
    Mexico      1500          
    Ireland      1000      
    SQL Generated:
    WITH
    SAWITH0 AS (select T95996.COUNTRY_NAME as c2,
    T95996.COUNTRY_CODE as c3,
    sum(T158903.HEADCOUNT) as c4,
    T100027.PER_NAME_MONTH as c5
    from
    W_BUSN_LOCATION_D T95996,
    W_EMPLOYMENT_D T95816,
    W_MONTH_D T100027,
    W_WRKFC_EVT_MONTH_F T158903
    where ( T95816.ROW_WID = T158903.EMPLOYMENT_WID
    and T95996.ROW_WID = T158903.LOCATION_WID
    and T100027.ROW_WID = T158903.EVENT_MONTH_WID
    and T100027.PER_NAME_MONTH = '2011 / 08'
    group by T95996.COUNTRY_CODE, T95996.COUNTRY_NAME, T100027.PER_NAME_MONTH),
    SAWITH1 AS (select distinct SAWITH0.c2 as c1,
    LAST_VALUE(SAWITH0.c4 IGNORE NULLS) OVER (PARTITION BY SAWITH0.c3 ORDER BY SAWITH0.c3 NULLS FIRST, SAWITH0.c5 NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as c2,
    SAWITH0.c3 as c3
    from
    SAWITH0)
    select SAWITH1.c1 as c1,
    SAWITH1.c2 as c2
    from
    SAWITH1
    order by c1
    When I create a report using Country Region, Headcount ( Month = July 11) I get wrong aggregation and all rows show same number
    Region 1- 135000
    Region 2- 135000
    Region 3- 135000
    SQL Generated:
    WITH
    SAWITH0 AS (select T95996.COUNTRY_REGION as c2,
    sum(T158903.HEADCOUNT) as c3,
    T100027.PER_NAME_MONTH as c4
    from
    W_EMPLOYMENT_D T95816,
    W_MONTH_D T100027,
    W_WRKFC_EVT_MONTH_F T158903,
    W_BUSN_LOCATION_D T95996
    where ( T95816.ROW_WID = T158903.EMPLOYMENT_WID
    and T100027.ROW_WID = T158903.EVENT_MONTH_WID
    and T100027.PER_NAME_MONTH = '2011 / 08'
    group by T95996.COUNTRY_REGION, T100027.PER_NAME_MONTH)
    select distinct SAWITH0.c2 as c1,
    LAST_VALUE(SAWITH0.c3 IGNORE NULLS) OVER ( ORDER BY SAWITH0.c4 NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as c2
    from
    SAWITH0
    order by c1
    I see that the second SQL is missing that PARTITION BY CLAUSE and wondering if this is reason for wrong calculation. How can I make BI Server to include this clause?
    Any leads will be helpful.

    Hi Deepak,
    Thanks for your reply. I see your point here.
    Some more info: This fact table is actually a monthly snapshot. Do you think I should check on anything else?
    I tried to simply the SQL Generated by I Server by removing some extra conditions. Here is the actual SQL for Country, Headcount:
    WITH
    SAWITH0 AS (select T95996.COUNTRY_NAME as c2,
    T95996.COUNTRY_CODE as c3,
    sum(case when T95816.W_EMPLOYMENT_STAT_CODE = 'A' and T95816.W_EMPLOYEE_CAT_CODE = 'EMPLOYEE' then T158903.HEADCOUNT else 0 end ) as c4,
    T100027.PER_NAME_MONTH as c5
    from
    W_BUSN_LOCATION_D T95996 /* Dim_W_BUSN_LOCATION_D_Employee */ ,
    W_EMPLOYMENT_D T95816 /* Dim_W_EMPLOYMENT_D */ ,
    W_MONTH_D T100027 /* Dim_W_MONTH_D */ ,
    W_WRKFC_EVT_MONTH_F T158903 /* Fact_W_WRKFC_EVT_MONTH_F_Snapshot */
    where ( T95816.ROW_WID = T158903.EMPLOYMENT_WID and T95996.ROW_WID = T158903.LOCATION_WID and T100027.ROW_WID = T158903.EVENT_MONTH_WID and T100027.PER_NAME_MONTH = '2011 / 07' and T158903.SNAPSHOT_IND = 1 and T158903.DELETE_FLG <> 'Y' and T100027.CAL_MONTH_START_DT >= TO_DATE('2004-01-01 00:00:00' , 'YYYY-MM-DD HH24:MI:SS') and (T158903.SNAPSHOT_MONTH_END_IND in (1) or T158903.EFFECTIVE_END_DATE >= TO_DATE('2011-08-11 00:00:00' , 'YYYY-MM-DD HH24:MI:SS')) and (T95996.ROW_WID in (0) or T95996.BUSN_LOC_TYPE in ('EMP_LOC')) and T158903.EFFECTIVE_START_DATE <= TO_DATE('2011-08-11 00:00:00' , 'YYYY-MM-DD HH24:MI:SS') )
    group by T95996.COUNTRY_CODE, T95996.COUNTRY_NAME, T100027.PER_NAME_MONTH),
    SAWITH1 AS (select distinct SAWITH0.c2 as c1,
    LAST_VALUE(SAWITH0.c4 IGNORE NULLS) OVER (PARTITION BY SAWITH0.c3 ORDER BY SAWITH0.c3 NULLS FIRST, SAWITH0.c5 NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as c2,
    SAWITH0.c3 as c3
    from
    SAWITH0)
    select SAWITH1.c1 as c1,
    SAWITH1.c2 as c2
    from
    SAWITH1
    order by c1
    for Country Region, Headcount:
    WITH
    SAWITH0 AS (select T95996.COUNTRY_REGION as c2,
    sum(case when T95816.W_EMPLOYMENT_STAT_CODE = 'A' and T95816.W_EMPLOYEE_CAT_CODE = 'EMPLOYEE' then T158903.HEADCOUNT else 0 end ) as c3,
    T100027.PER_NAME_MONTH as c4
    from
    W_EMPLOYMENT_D T95816 /* Dim_W_EMPLOYMENT_D */ ,
    W_MONTH_D T100027 /* Dim_W_MONTH_D */ ,
    W_WRKFC_EVT_MONTH_F T158903 /* Fact_W_WRKFC_EVT_MONTH_F_Snapshot */ ,
    W_BUSN_LOCATION_D T95996 /* Dim_W_BUSN_LOCATION_D_Employee */
    where ( T95816.ROW_WID = T158903.EMPLOYMENT_WID and T100027.ROW_WID = T158903.EVENT_MONTH_WID and T100027.PER_NAME_MONTH = '2011 / 07' and T158903.SNAPSHOT_IND = 1 and T158903.DELETE_FLG <> 'Y' and T100027.CAL_MONTH_START_DT >= TO_DATE('2004-01-01 00:00:00' , 'YYYY-MM-DD HH24:MI:SS') and (T158903.SNAPSHOT_MONTH_END_IND in (1) or T158903.EFFECTIVE_END_DATE >= TO_DATE('2011-08-11 00:00:00' , 'YYYY-MM-DD HH24:MI:SS')) and (T95996.ROW_WID in (0) or T95996.BUSN_LOC_TYPE in ('EMP_LOC')) and T158903.EFFECTIVE_START_DATE <= TO_DATE('2011-08-11 00:00:00' , 'YYYY-MM-DD HH24:MI:SS') )
    group by T95996.COUNTRY_REGION, T100027.PER_NAME_MONTH)
    select distinct SAWITH0.c2 as c1,
    LAST_VALUE(SAWITH0.c3 IGNORE NULLS) OVER ( ORDER BY SAWITH0.c4 NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as c2
    from
    SAWITH0
    order by c1

  • Partition by clause

    Dose the Partition by clause increase the perfomance then the normal group by clause ??
    thanks,
    Raj.

    Analytic queries != Aggregate queries
    Therefore it depends on what you're doing as to whether you'd want to use Analytic vs Aggregate queries.
    Performance depends also on the amount of data in your tables.
    Having said that, Analytics can mean that a self-join is no longer needed, and this could help if a large table is involved ... on the otherhand, it might hinder.
    Think of Analytic queries as another tool in your toolbox; sometimes a hammer is the right tool to use, but sometimes you need a spanner instead.

  • Group by and order by clause

    Hi,
    I have wriiten the below query and i am using group by and order by clause....but i am not getting the required result
    SELECT b.ACCOUNT_REGION,CASE WHEN b.product_reference_status='Reference' THEN 'Recruited' WHEN b.product_reference_status in ('Inactive','Declined') THEN 'Inactive' WHEN b.product_reference_status ='Nominate' THEN 'Inprogress' ELSE 'Other' END product_reference_status, COUNT(decode(b.product_quarter,'Q1FY09',b.REFERENCE_ID)) Q1FY09, COUNT(decode(b.product_quarter,'Q2FY09',b.REFERENCE_ID)) Q2FY09, COUNT(decode(b.product_quarter,'Q3FY09',b.REFERENCE_ID)) Q3FY09, COUNT(decode(b.product_quarter,'Q4FY09',b.REFERENCE_ID)) Q4FY09, COUNT(decode(b.product_quarter,'Q1FY10',b.REFERENCE_ID)) Q1FY10, COUNT(decode(b.product_quarter,'Q2FY10',b.REFERENCE_ID)) Q2FY10, COUNT(decode(b.product_quarter,'Q3FY10',b.REFERENCE_ID)) Q3FY10, COUNT(decode(b.product_quarter,'Q4FY10',b.REFERENCE_ID)) Q4FY10, COUNT(b.product_quarter) Total
    FROM refdump a, ref_dh_pr b
    WHERE A.REFERENCE_ID=b.REFERENCE_ID AND (b.CREATED_ON - NVL(a.REFERENCE_DATE,a.CREATED))>15 group by b.account_region,product_reference_status order by 2
    output is as given below
    Region Status Count
    LAD     Inactive     0
    EMEA     Inactive     21
    *APAC     Inactive     2
    *APAC     Inactive     1
    EMEA     Inactive     2
    EMEA     Inprogress     220
    LAD     Inprogress     19
    LAD     Other     2
    LAD     Other     0
    LAD     Other     5
    LAD     Recruited     182
    APAC     Recruited     191
    My question is
    1) Why i am geeting two APAC regions and 3 LAD (marked *) regions when i have grouped by region and status
    2) How can i make the status in the following order
    a) Recruited
    b)Inprogress
    c)Inactive
    d)Other
    Thanks,

    <i>group by b.account_region,product_reference_status</i>
    Just take all the columns in the group by clause in your select segment and run the SQL, you'll come to know abt the different values in columns which group together.
    *009*

  • Cross-listing Query (Partition By Clause? Self-Join?)

    Hello,
    I need a query that will cross-list courses a professor is teaching this semester. Essentially, two fields need to be the same (i.e.: Section & CourseTitle), while the third field is different (i.e.: Subject).
    For example, Max Power is a professor teaching 3 courses, one is cross-listed (ENG 123 and JRL 123):
    LastName     FirstName     Subject     Section     CourseTitle
    Power          Max          ENG     123     English Composition
    Power          Max          ENG     452     Robert Frost Poetry     
    Power          Max          JRL     123     English Composition
    Power           Max          ENG      300     Faulkner & TwainThe desired query output is this:
    LastName     FirstName     Subject     Section     CourseTitle
    Power          Max          ENG     123     English Composition
    Power          Max          JRL     123     English CompositionBasically, I need only the cross-listed courses in the output.Is this an instance where I use a "Partition By Clause" or should I create a self-join?
    Much thanks for any help and comments.

    Unfortunately, I can't create new tables. I don't have permission. I can't alter, add or delete any of the data.
    So I tried Frank's code with my data:
    WITH got_cnt AS
    SELECT  sivasgn_term_code, spriden_id, spriden_last_name, spriden_first_name,
                    ssbsect_ptrm_code, ssbsect_camp_code,
                    sivasgn_crn, ssbsect_subj_code, ssbsect_crse_numb, scbcrse_title,
           count(*) over (partition by ssbsect_crse_numb, scbcrse_title) cnt
    FROM spriden INNER JOIN sivasgn ON spriden_pidm = sivasgn_pidm JOIN
         ssvsect ON ssbsect_crn = sivasgn_crn JOIN
         sfrstcr ON sfrstcr_crn = sivasgn_crn
    WHERE  ssbsect_term_code= sivasgn_term_code  
    AND sfrstcr_term_code = sivasgn_term_code
    AND ssbsect_enrl > '0' and sivasgn_credit_hr_sess > '0'
    AND sivasgn_term_code IN ('200901', '200909')
    AND spriden_change_ind IS NULL
    AND ssbsect_camp_code IN ('1', '2', 'A', 'B')
    SELECT DISTINCT sivasgn_term_code, spriden_id, spriden_last_name, spriden_first_name,
                    substr(ssbsect_ptrm_code,1,1) as ptrm_code, ssbsect_camp_code,
                    sivasgn_crn, ssbsect_subj_code, ssbsect_crse_numb, scbcrse_title
    FROM got_cnt
    WHERE cnt >1
    ORDER BY spriden_last_name, sivasgn_term_code, ssbsect_crse_numb;The output pretty much displays all courses with same subject code, course number and course title.
    Output:
    LastName     FirstName     Subject     Section     CourseTitle
    Power          Max          ENG     123     English Composition
    Power          Max          ENG     123     English Composition
    Power          Max          ENG     452     Robert Frost Poetry
    Power          Max          ENG     452     Robert Frost Poetry
    Power           Max          ENG      300     Faulkner & Twain
    Power           Max          ENG      300     Faulkner & Twain
    Power          Max          JRL     123     English Composition
    Power          Max          JRL     123     English CompositionWhat I would like is same course number, course title, BUT different subject code. Pretty much that in my first post of this thread.
    Desired Output:
    LastName     FirstName     Subject     Section     CourseTitle
    Power          Max          ENG     123     English Composition
    Power          Max          JRL     123     English CompositionMaybe I'm explaining this wrong. Any help would be greatly appreciated. Thanks.

  • Difference in number of records in GROUP BY and PARTITION BY

    Hi Experts
    If I run the following query I got 997 records by using GROUP BY.
    SELECT c.ins_no, b.pd_date,a.project_id,
    a.tech_no
    FROM mis.tranche_balance a,
    FMSRPT.fund_reporting_period b,
    ods.proj_info_lookup c,
    ods.institution d
    WHERE a.su_date = b.pd_date
    AND a.project_id = c.project_id
    AND c.ins_no = d.ins_no
    AND d.sif_code LIKE 'P%'
    AND d.sif_code <> 'P-DA'
    AND a.date_stamp >='01-JAN-2011'
    AND pd_date='31-MAR-2011'
    GROUP BY c.ins_no,
    b.pd_date,
    a.project_id,
    a.tech_no;
    I want to show the extra columns a.date_stamp and a.su_date
    in the out put so that I have used PARTITION BY in the second query but I got 1079 records.
    SELECT c.ins_no, b.pd_date,a.date_stamp,a.su_date, a.project_id,
    a.tech_no,
    COUNT(*) OVER(PARTITION BY c.ins_no,
    b.pd_date,
    a.project_id,
    a.tech_no)c
    FROM mis.tranche_balance a,
    FMSRPT.fund_reporting_period b,
    ods.proj_info_lookup c,
    ods.institution d
    WHERE a.su_date = b.pd_date
    AND a.project_id = c.project_id
    AND c.ins_no = d.ins_no
    AND d.sif_code LIKE 'P%'
    AND d.sif_code <> 'P-DA'
    AND a.date_stamp >='01-JAN-2011'
    AND pd_date='31-MAR-2011'
    Please help me why I got 1079 records.
    And also please help me how to show the two extra columns in the out put whcich are not used in
    GROUP BY clause.
    Thanks in advance.

    Hi,
    user9077483 wrote:
    Hi Experts
    If I run the following query I got 997 records by using GROUP BY. ...Let''s call this "Query 1", and the number of rows it returns "N1".
    The results tell you that there are 997 distinct combinations of the GROUP BY columns (c.ins_no, b.pd_date, a.project_id, a.tech_no).
    I want to show the extra columns a.date_stamp and a.su_date
    in the out put so that I have used PARTITION BY in the second query but I got 1079 records. ...Let's call the query without the GROUP BY "Query 2", and the number of rows it returns "N2".
    Please help me why I got 1079 records.Because there are 1079 rows that meet all the GROUP BY conditions. Query 2 has nothing to with distinct values in any columns. You would expect that N2 to be at least as high as N1, but it's not surprising that the N2 is higher than N1.
    And also please help me how to show the two extra columns in the out put whcich are not used in
    GROUP BY clause.Doesn't Query 2 show those two columns already? If the Query 2 is not producing the results you want, then what results do you want?
    Post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    Explain, using specific examples, how you get those results from that data. Point out a couple of places where Query 2 is not doing what you want.
    Always say which version of Oracle you're using.

  • Help !!!  - partition by  clause

    hi. i have the following table
    table : item_tracker
    date | item_code | begin_price
    end of each day, one record for each item is getting written to this table. now after the records are written, i want to calculate the change in begin prices
    the formula is change_in_price=(todays_begin / yesterdays_begin) * 100
    i wrote the following query but it seems not working. please advise me on what i am doing wrong.. also is the approach wrong ?
    please advise.
    select date, item_code, begin_price, first_value(begin_price) over (partition by date, item_code order by trunc(date) desc rows between 2 preceding and 1 preceding) as yesterdays_begin
    from item_tracker
    here, the partition by column is not showing any value.
    is there any way i can include the date ? (like a 'having clause' for group by, what is the method to partition by)
    i tried range between as well. it reurned the error that i need to mention a number value instead of date to check a range.
    please help me :(
    thanx in advance

    Yes, joins are effective :
    SQL> create table item_tracker(price_date date, item_id number, day_price number);
    Table created.
    SQL> insert into item_tracker values ('11-JAN-11',1,10);
    1 row created.
    SQL> insert into item_tracker values ('11-JAN-11',2,12);
    1 row created.
    SQL> insert into item_tracker values ('11-JAN-11',3,24);
    1 row created.
    SQL> insert into item_tracker values ('12-JAN-11',1,10.5);
    1 row created.
    SQL> insert into item_tracker values ('12-JAN-11',2,16);
    1 row created.
    SQL> insert into item_tracker values ('12-JAN-11',3,21);
    1 row created.
    SQL> commit;
    Commit complete.
    SQL>
    SQL> l
      1  select a.item_id, a.price_date, a.day_price, b.day_price PrevPrice, (a.day_price - b.day_price) PriceDiff
      2  from item_tracker a, item_tracker b
      3  where a.item_id=b.item_id
      4  and a.price_date=to_date('12-JAN-11','DD-MON-RR')
      5  and b.price_date=a.price_date-1
      6* order by 1
    SQL> /
       ITEM_ID PRICE_DAT  DAY_PRICE  PREVPRICE  PRICEDIFF
             1 12-JAN-11       10.5         10         .5
             2 12-JAN-11         16         12          4
             3 12-JAN-11         21         24         -3
    SQL>Hemant K Chitale

  • Logical Volume Group and Logical Partition not matching up in free space

    I was dual booting Windows 7 and Mountain Lion. Through Disk Utility, I removed the Windows 7 Partition and expanded the HFS+ partition to encompass the entire hard drive. However, the Logical Volume Group does not think that I have that extra free space. The main problem is that I cannot resize my partition. I am wanting to dual boot Ubuntu with this. Any ideas? Any help is appreciated. I will post some screenshots with the details. Furthermore, here are some terminal commands I ran: /dev/disk0
    #: TYPE NAME SIZE IDENTIFIER
    0: GUID_partition_scheme *250.1 GB disk0
    1: EFI 209.7 MB disk0s1
    2: Apple_CoreStorage 249.2 GB disk0s2
    3: Apple_Boot Recovery HD 650.0 MB disk0s3
    /dev/disk1
    #: TYPE NAME SIZE IDENTIFIER
    0: Apple_HFS MAC OS X *248.9 GB disk1 Filesystem 1024-blocks Used Available Capacity iused ifree %iused Mounted on
    /dev/disk1 243031288 153028624 89746664 64% 38321154 22436666 63% /
    devfs 189 189 0 100% 655 0 100% /dev
    map -hosts 0 0 0 100% 0 0 100% /net
    map auto_home 0 0 0 100% 0 0 100% /home CoreStorage logical volume groups (1 found)
    |
    +-- Logical Volume Group 52A4D825-B134-4C33-AC8B-39A02BA30522
    =========================================================
    Name: MAC OS X
    Size: 249199587328 B (249.2 GB)
    Free Space: 16777216 B (16.8 MB)
    |
    +-< Physical Volume 6D7A0A36-1D86-4A30-8EB5-755D375369D9
    | ----------------------------------------------------
    | Index: 0
    | Disk: disk0s2
    | Status: Online
    | Size: 249199587328 B (249.2 GB)
    |
    +-> Logical Volume Family FDC4568F-4E25-46AB-885A-CBA6287309B6
    Encryption Status: Unlocked
    Encryption Type: None
    Conversion Status: Converting
    Conversion Direction: backward
    Has Encrypted Extents: Yes
    Fully Secure: No
    Passphrase Required: No
    |
    +-> Logical Volume BB2662B7-58F3-401C-B889-F264D79E68B4
    Disk: disk1
    Status: Online
    Size (Total): 248864038912 B (248.9 GB)
    Size (Converted): 130367356928 B (130.4 GB)
    Revertible: Yes (unlock and decryption required)
    LV Name: MAC OS X
    Volume Name: MAC OS X
    Content Hint: Apple_HFS

    Here is another try via the command line:
    dhcp-10-201-238-248:~ KyleWLawrence$ diskutil coreStorage resizeVolume BB2662B7-58F3-401C-B889-F264D79E68B4 210g
    Started CoreStorage operation
    Checking file system
    Performing live verification
    Checking Journaled HFS Plus volume
    Checking extents overflow file
    Checking catalog file
    Incorrect block count for file 2012.12.11.asl
    (It should be 390 instead of 195)
    Checking multi-linked files
    Checking catalog hierarchy
    Checking extended attributes file
    Checking volume bitmap
    Checking volume information
    Invalid volume free block count
    (It should be 21713521 instead of 21713716)
    The volume MAC OS X was found corrupt and needs to be repaired
    Error: -69845: File system verify or repair failed

  • Failed to revert logical volume group while merging partition

    Hi All,
    Previously, on my macbook pro, I partitioned my disk for win7 for my dual operation system and only left 120 GB for OS, now I want to delete win7 and return disk space to OS. Currently my OS is yosemite.
    I have already deleted disk space for win7 and merged it back to disk0s3. And, I had a problem to merge disk0s2 with disk0s3.
    I was told it is because I need to revet my Logical Volume Group. I am blocked at reverting it.
    This is my disk info:
    rescomp-14-251133:~ rico$ diskutil list; diskutil  cs list
    /dev/disk0
       #:                       TYPE NAME                    SIZE       IDENTIFIER
       0:      GUID_partition_scheme                        *500.1 GB   disk0
       1:                        EFI EFI                     209.7 MB   disk0s1
       2:          Apple_CoreStorage                         119.3 GB   disk0s2
       3:                  Apple_HFS Recovery HD             380.6 GB   disk0s3
    /dev/disk1
       #:                       TYPE NAME                    SIZE       IDENTIFIER
       0:                  Apple_HFS Macintosh HD           *119.0 GB   disk1
                                     Logical Volume on disk0s2
                                     CC457129-6FE9-41A0-B0D2-F547F21A7555
                                     Unencrypted
    CoreStorage logical volume groups (1 found)
    |
    +-- Logical Volume Group F454017F-C531-43BA-B270-E2058E05BFF4
        =========================================================
        Name:         Macintosh HD
        Status:       Online
        Size:         119290187776 B (119.3 GB)
        Free Space:   4096 B (4.1 KB)
        |
        +-< Physical Volume AC7A2748-0DA1-49D6-B50C-30348838760E
        |   ----------------------------------------------------
        |   Index:    0
        |   Disk:     disk0s2
        |   Status:   Online
        |   Size:     119290187776 B (119.3 GB)
        |
        +-> Logical Volume Family 4B7E6277-69BC-475A-BBB7-7A94D6434D9E
            Encryption Status:       Unlocked
            Encryption Type:         AES-XTS
            Conversion Status:       Converting
            Conversion Direction:    -none-
            Has Encrypted Extents:   Yes
            Fully Secure:            No
            Passphrase Required:     No
            |
            +-> Logical Volume CC457129-6FE9-41A0-B0D2-F547F21A7555
                Disk:                  disk1
                Status:                Online
                Size (Total):          118954639360 B (119.0 GB)
                Conversion Progress:   -none-
                Revertible:            Yes (unlock and decryption required)
                LV Name:               Macintosh HD
                Volume Name:           Macintosh HD
                Content Hint:          Apple_HFS
    when I type unlock:
    rescomp-14-251133:~ rico$ diskutil corestorage unlockVolume CC457129-6FE9-41A0-B0D2-F547F21A7555 -stdinpassphrase
    CC457129-6FE9-41A0-B0D2-F547F21A7555 is already unlocked and is attached as disk1
    It is already unlocked
    then, I tried revert it
    rescomp-14-251133:~ rico$ diskutil coreStorage revert CC457129-6FE9-41A0-B0D2-F547F21A7555
    Passphrase:
    Started CoreStorage operation on disk1 Macintosh HD
    Error: -69750: Unable to modify a FileVault context
    Does anyone how I can revert it, then merge disk0s2 and disk0s3

    Here is another try via the command line:
    dhcp-10-201-238-248:~ KyleWLawrence$ diskutil coreStorage resizeVolume BB2662B7-58F3-401C-B889-F264D79E68B4 210g
    Started CoreStorage operation
    Checking file system
    Performing live verification
    Checking Journaled HFS Plus volume
    Checking extents overflow file
    Checking catalog file
    Incorrect block count for file 2012.12.11.asl
    (It should be 390 instead of 195)
    Checking multi-linked files
    Checking catalog hierarchy
    Checking extended attributes file
    Checking volume bitmap
    Checking volume information
    Invalid volume free block count
    (It should be 21713521 instead of 21713716)
    The volume MAC OS X was found corrupt and needs to be repaired
    Error: -69845: File system verify or repair failed

  • How Will Yosemite Logical Volume Group Affect Two-Partition Drive?

    After installing Yosemite, my Macintosh HD became a Logical Volume Group. Now, in Disk Utility, both the Drive and the Volume have the same name — Macintosh HD. I want to use one of two partitions on an extra internal drive in my Mac Pro (Mid 2010) as a bootable clone of my Yosemite startup drive, using SuperDuper!. When cloning is complete, will my spare drive become a Logical Volume Group with a renamed drive? Will that effect the other partition, which is a bootable Mavericks clone?

    Thanks for the tip. I see its a common trouble. But i stuck a problem that cannot be solved with this method cause i dont have revertable logic volume.
    SO i cannot install system now. There's  no visible disk any more.

  • GROUP By function in where clause

    Hi,
    I have a table which stores student marks.
    Student Table
    STD_ID STD_MARK
    1 10
    2 20
    3 5
    I want to find the student who got the the highst marks with and SQL select statement. This is what I wrote.
    SELECT STD_ID from Student where STD_MARK=MAX(STD_MARK)
    But oracle gives an error saying group function is not allowed here.
    Can u plz tell me how to get the student who has got the highst marks.
    Chamal.

    Did you get an answer as to how to return only one
    row per student?
    I have the same problem and have been spinning my
    wheels.
    select * from table
    where action_ind = 'N'
    group by employee_id
    I get 4 rows per person and all I need is any 1 for
    that employee_id.
    rjdizolwell, this is a new question... but you cannot use rownum there, use analytics instead, and partition by grouping column
    ex:
    SQL> select ename, deptno, sal from (
        select row_number() over (partition by deptno order by sal desc) r, emp.* from emp)
    where r=1;
    ENAME          DEPTNO        SAL
    KING               10       5000
    SCOTT              20       3000
    BLAKE              30       2850

  • Non-group-by expression in select clause

    Hi ya'll.  I am new at writing SQL commands and am running into an error that I don't understand.  I am trying to insert a simple 'GROUP BY' clause and keep getting the above error.  I can insert the ORDER BY clause without any error, but when I add the GROUP BY clause it  causes the error. 
    It is a very basic report with only two tables and one LEFT JOIN.  I will insert a copy of the SQL command below.
    Thank you very much for any help you can provide.
    Marlene Allen
    Crystal Reports Professional -FULL type
    Product Version: 11.5
    SELECT
    sm_cntrt.scm_ctr_dt,
    sm_cntrt.scm_ctr_no,
    sm_cntrt.scm_cntrgrp,
    sm_cntrt.div,
    sm_cntrt.scm_renew_no,
    sm_cstdt.scd_wo_no,
    sm_cstdt.scd_fisc_dt,
    sm_cstdt.scd_jc_cat,
    sm_cstdt.scd_ovt_hrs,
    sm_cstdt.scd_reg_hrs,
    sm_cstdt.scd_ctr_empm
    FROM
    sm_cntrt
    LEFT JOIN
    sm_cstdt on sm_cntrt.scm_ctr_no = sm_cstdt.scd_ctr_no
    WHERE
    sm_cntrt.scm_active = 'a' and
    year(sm_cstdt.scd_fisc_dt) is NULL OR
    sm_cntrt.scm_active = 'a' and
    year(sm_cstdt.scd_fisc_dt) = year(curdate()) and
    month(sm_cstdt.scd_fisc_dt) <= month(curdate())-1 and                         
                                 scd_rtype <> 2 and
                                 scd_jc_cat = 'la'
    GROUP by
    sm_cntrt.scm_ctr_no
    ORDER BY
    sm_cntrt.scm_cntrgrp,sm_cntrt.scm_ctr_no

    Marlene,
    Ian is correct. The GROUP BY clause is used to perform aggregate functions withing the SQL. For it to work, EVERY field in the SELECT list must be either aggregated or included in the GROUP BY list.
    I'd disagree with the Ian's assertion that you don't need to use the ORDER BY clause... Database servers are typically better at sorting large record sets than a pc running CR... So while you don't NEED to sort using the ORDER BY clause, it can speed up processing time when working with larger record sets.
    Jason

  • Group by caluse before where clause

    Hi all,
    Declare
    cursor c1 is select ARc_Month as mnth,count(*) as nof from dbarc
    group by ARc_Month
    where ARc_Month like '%02%';
    e1 varchar2(1000);
    cnt number(10);
    begin
    e1:='1';
    for crec in c1 loop
    cnt:= c1%rowcount;
    dbms_output.put_line(cnt||'------'||crec.mnth||'-------'||crec.nof);
    end loop;
    end ;
    Please go through the select statement for the cursor C1 which is syntactically worng but, the cursor is giving correct data. If the same select statement is run independently i.e at the sql prompt then it giving the following error, I knew that the error is due to the group by clause is before where clause. but it is not giving error while executing using explicit cursor.
    SQL> select arc_month as mnth,count(*) as nof from dbarc
    2 group by arc_month
    3 where arc_month like '%02%';
    where arc_month like '%02%'
    ERROR at line 3:
    ORA-00933: SQL command not properly ended
    can anybody resolve this ambiguity. my oracle version is 8.1.7, Is this a known bug or unknown
    Thanks in advance.

    Ram
    Yes, I get the same, also on 8.1.7. I can only guess they have changed pl/sql to relax the syntax restriction but have not got around to putting it in sql yet.
    SQL> list
    1 begin
    2 declare cursor x is
    3 select dummy from dual
    4 group by dummy
    5 where dummy is not null;
    6 thing varchar2(1);
    7 begin
    8 open x;
    9 fetch x into thing;
    10 end;
    11* end;
    SQL> /
    PL/SQL procedure successfully completed.
    SQL> select dummy from dual
    2 group by dummy
    3 where dummy is not null;
    where dummy is not null
    ERROR at line 3:
    ORA-00933: SQL command not properly ended

Maybe you are looking for