PARTITION BY ? Return an ID based on the minimum value of another column

Hi guys
I want to return the ID column of a row, where 2 other columns = a set value, and a 3rd column has the minimum value matching the other criteria.
so in effect :
with t as (
select 1 dst_id, 'abc' dst_title, 1 edition_from, 1 media_item from dual
union all
select 2 dst_id, 'abc' dst_title, 1 edition_from, 2 media_item from dual
union all
select 3 dst_id, 'abc' dst_title, 2 edition_from, 1 media_item from dual
union all
select 4 dst_id, 'abc' dst_title, 2 edition_from, 2 media_item from dual
union all
select 5 dst_id, 'def' dst_title, 1 edition_from, 1 media_item from dual
union all
select 6 dst_id, 'def' dst_title, 1 edition_from, 2 media_item from dual
  select dst_id
  from t
  where dst_title = 'abc'
  and edition_from = 1
  and media_item = minimum value of media item using above where clauseWould return dst_id = 1 because it has the minimum media item value of 1 where dst_title = abc and edition_from = 1
Can this be done in 1 query ? I've been trying it using partition by and over dst_title, edition_from but that doesn't work.
I'm currently doing it using a sub query or 2 queries, but thought there must be a way to do it in one ?
Thanks all
Scott

Like this?
SQL> with t as (
  2  select 1 dst_id, 'abc' dst_title, 1 edition_from, 1 media_item from dual
  3  union all
  4  select 2 dst_id, 'abc' dst_title, 1 edition_from, 2 media_item from dual
  5  union all
  6  select 3 dst_id, 'abc' dst_title, 2 edition_from, 1 media_item from dual
  7  union all
  8  select 4 dst_id, 'abc' dst_title, 2 edition_from, 2 media_item from dual
  9  union all
10  select 5 dst_id, 'def' dst_title, 1 edition_from, 1 media_item from dual
11  union all
12  select 6 dst_id, 'def' dst_title, 1 edition_from, 2 media_item from dual
13  )
14  select dst_id
15  from (select t.*
16        ,      row_number() over (partition by dst_title, edition_from order by media_item) rn
17        from   t
18        where  dst_title = 'abc'
19        and    edition_from = 1)
20  where rn = 1;
    DST_ID
         1
SQL>

Similar Messages

  • Update a row based on the minimum value

    I need to update a row value in a table (table1) which is having one-to-may relationship with another table (table2) based on priority. Below is the table structure and sample data. I have a merge statement which can just do this, but it's taking too much to execute if the data in table2 is huge.
    I want to reduce the execution time, can anyone suggest me another way to do this.
    --Table Definition
    CREATE TABLE TABLE_1 (ENAME VARCHAR2(20), ID NUMBER(20), DISPLAY_NAME VARCHAR2(20), PRIMARY KEY (ENAME));
    CREATE TABLE TABLE_2 (ENAME VARCHAR2(20), DISPLAY_NAME VARCHAR2(20), PRIORITY NUMBER(1));
    --Sample data
    INSERT INTO TABLE_1 (ENAME,ID) VALUES ('EMP1','1000');
    INSERT INTO TABLE_1 (ENAME,ID) VALUES ('EMP2','2000');
    INSERT INTO TABLE_2 (ENAME,DISPLAY_NAME,PRIORITY) VALUES ('EMP1','APPLE',1);
    INSERT INTO TABLE_2 (ENAME,DISPLAY_NAME,PRIORITY) VALUES ('EMP1','DELL',2);
    INSERT INTO TABLE_2 (ENAME,DISPLAY_NAME,PRIORITY) VALUES ('EMP1','MS',NULL);
    --Merge to perfor the update
    MERGE INTO TABLE_1 T USING
    (select ename, display_name from TABLE_2 where (ename,priority) in (
    select distinct ename, min(priority) over (partition by ename) from TABLE_2 min_prior)) Q
    ON (T.ENAME = Q.ENAME)
    WHEN MATCHED THEN UPDATE SET DISPLAY_NAME = Q.DISPLAY_NAME;

    Hi,
    You can use the aggregate FIRST function, like this:
    MERGE INTO     table_1          t
    USING   (
             SELECT    ename
             ,            MIN (display_name) KEEP (DENSE_RANK FIRST ORDER BY priority)     
                              AS first_display_name
             FROM      table_2
             GROUP BY  ename
         )               q
    ON      (t.ename = q.ename)
    WHEN MATCHED THEN UPDATE
    SET      t.display_name      = q.first_display_name
    ;If the combination (ename, priority) is not unique in table_2, then this uses the first display_name (in normal sort order) among those with the lowest priority. This probably can't happen, becuase your original statement would raise an error if it did.
    For performance problems, see the forum FAQ {message:id=9360003}

  • Update column based on a parsed value from another column

    <p>i have table1 which has&nbsp;description, region and division columns.&nbsp;If the "description like '% (%.% or %.%'" I want to parse the first '%.%' which has the values for&nbsp;'region.division' and update the table1.region
    and table1.division columns. </p><p></p><p>FOR EXAMPLE</p><p>DESCRIPTION, REGION, DIVISION</p><p>Total Employes (SouthEast.Florida or 111.22),,</p><p>WANT IT AS</p><p>Total Employes (SouthEast.Florida
    or 111.22),SouthEast,Florida</p><p>thanks in advance.</p><p></p>

    In my tests the following update of CTE works fine. Hopefully this will work for the real table as well although it is a good idea to always have primary key:
    DECLARE @t TABLE (
    DESCRIPTION VARCHAR(200)
    ,REGION VARCHAR(30)
    ,DIVISION VARCHAR(30)
    INSERT INTO @t (
    DESCRIPTION
    ,REGION
    ,DIVISION
    VALUES (
    'Total Employes (SouthEast.Florida or 111.22)'
    'Test no info'
    WITH cteParsed
    AS (
    SELECT *
    ,CASE
    WHEN DESCRIPTION LIKE '%(%.%'
    THEN substring(description, charindex('(', DESCRIPTION) + 1, len(Description))
    ELSE NULL
    END AS StartInfo
    FROM @t
    WHERE DESCRIPTION LIKE '%(%.%'
    AND len(Region) = 0
    AND len(Division) = 0
    ,cte
    AS (
    SELECT *
    ,substring(StartInfo, 1, charindex(' ', StartInfo) - 1) AS Rest
    FROM cteParsed
    UPDATE cte
    SET region = substring(Rest, 1, charindex('.', Rest) - 1)
    ,division = substring(Rest, charindex('.', Rest) + 1, len(Rest))
    SELECT *
    FROM @t; -- verify the changes taken place
    For every expert, there is an equal and opposite expert. - Becker's Law
    My blog
    My TechNet articles

  • How to load DataBlock based on the Multiple Condition from another block

    Hi
    How to load a Data Block based on the Multiple values from another block. For eg.EMP is the Master Data block and SAL is the child Datablock.When query JOS% in the Master Block(EMP) then display all the Sal details in the SAL block for all the employees starting with JOS , When clicking one buton or if it is possible in the loadin of the MasterBlock

    Hi,
    I presume you are using database block relations.
    Put automatic query = yes in relation properties.
    Do you have block level trigger ON-POPULATE-DETAILS?
    In that you can find the relation and query - Using built-ins
    Find_Relation and Query_Master_Details

  • Is there a way to hide some reports based on the selected values in prompt.

    Hi Experts,
    Is there a way to hide some reports based on the selected values in prompt.
    For ex. if a year is selected in the prompt then the report should display year wise report.
    If a year and half year both are selected in the drop down from prompt section then 2 reports should come.. One for year wise and another for half year wise.Kindly look into this.
    Regards
    Ashish

    Hi,
    Use presentation values in prompts for year,half,qtr and month.Example- For year-y is presentation variable in the same way for halfyear-h,qtr-q and month-m.
    create four intermediate reports.Example-Report r1 with only year column,r2 with only halfyear column,r3 with qtr column and r4 with month column.
    Make column in each report(r1,r2,r3,r4) is equal to their presentation variables(y,h,q,m).
    Use four sections.
    Section1-Place report that should come when only year.
    section2-Place report that should come for year and halfyear.
    Section3-Place report that should come for year,halfyear and qtr.
    Section4-Place report that should come for year,halfyear,qtr and month.
    Apply guided navigation for each section selecting guided navigation-
    For section1-
    properties->Guided navigation->check this Reference Source Request(Yes)->select report r1(year)->check this Show Section(if request returns row)
    In the same way do for remaining section2(select r2),section3(select r3) and section4(select r4)
    Thanks,
    Srikanth
    http://bintelligencegroup.wordpress.com/

  • How to set a default value for a drop down list box and then apply cascading based on the default value in Infopath 2010.

    Hello Everyone
    I have two drop downs. Both are coming from look up fields from two lists. i want to set a default value(first list item) for the first drop down list box and then apply cascading based on the default value for the next drop down list box. I found one article(http://www.bizsupportonline.net/infopath2010/display-first-item-drop-down-list-box-infopath-2010.htm)
    where in i can set a default value but i can't apply cascading based on that default value. Any suggestions would be highly appreciated.
    Thanks
    Ramanjulu Naidu N

    Hey Ramanjulu,
    Take a look at the below article which I believe will answer your question.
    http://basquang.wordpress.com/2010/03/29/cascading-drop-down-list-in-sharepoint-2010-using-infopath-2010/
    Daniel Christian (MCTS)

  • How to find bpel instance in 11g based on the index values using Java APIs

    Hi ,
    In SOA10G we had option to find the instances based on the index value using Java APIs like below.
    WhereCondition criteria= new WhereCondition(SQLDefs.CX_index_1 + " = ?");
    criteria.setString(1, "indexValue");
    Locator mLoc = getLocator();
    IInstanceHandle[] foundInstances = mLoc.listInstancesByIndex(criteria);
    Please tell me how to achieve the same functionality in SOA 11G using Java APIs
    Regards,
    Saba

    I have multiple bpel in my composite. I checked in ci_indexes table and it shows the instance number of the bpel process. But the em console is showing only the composite instance number. when I opened composite instance, I could see all the bpel process with instance number in the audit trail. How can I find the the actual composite instance number that I should search for in the em console ???

  • Hide multiple rows in a dynamic table based on the row value.

    Hi,
    I need to hide multiple rows in a dynamic table based on the specific value of that row.
    I cant find the right expression to do that.
    please help

    Go to the Row Properties, and in the Visibility tab, you have "Show or hide based on an expression". You can use this to write an expression that resolves to true if the row should be hidden, false otherwise.
    Additionally, in the Matrix properties you should take a look at the filters section, perhaps you can achieve what you wish to achieve through there by removing the unnecessary rows instead of just hiding them.
    It's only so much I can help you with the limited information. If you require further help, please provide us with more information such as what data are you displaying, what's the criteria to hiding rows, etc...
    Regards
    Andrew Borg Cardona

  • Freight Calculation based on the net value of the Line item

    Hi SAP Gurus,
    I have one requirement for Freight calculation(Sales order is created through an IDOC) :
    In the idoc,we will receive a freight dollar amount - which will be the total amount of freight.(example 100)
    We will also receive sales dollar for each line item ,which is then passed to the pricing procedure, for a total amount of sales for that Sales order.
    (examples below, for a total of 1500)
    The 100  is to be posted to a freight G/L account.
    The 100 is further divided by each profit center  of the materials on the Sales order.
    The freight is split out amongst the  profit center , based on the net value of the line item.
    Freight value to be allocated = Line item value/total value of the sales order * Freight amount.
    Total of the sales order =1500
         Line item value     Freight value calculation     Profit center
    Material A:      800          800/1500*100  = 53     Profit center A
    Material B:     500          500/1500*100  = 33     Profit center B
    Material C:      200          200/1500*100  = 13     Profit center C
    Please let me know how to achieve this functionality in pricing procedure or what changes i need to make in Freight condition type.
    Thanks in advance,
    Bhakar Saha

    Were you able to resolve this issue of allocating freight costs to line items/profit centers using the net value of the line items?

  • Dist. of Header Condition based on the material Value

    Hi All,
    I have one query regarding the header Condition.i have selected the Calculation type as B - fixed amount  (mandatory) for a particular Condition type and also selected the header and Item condition indicator.Now if the material have more than one line item then the system distributes this condition based on the quantities in PO.
    My client requirement is that they want to have a header condition as we are using now. But they want to distribute this header condition according to the material values for each line items in a PO. please Mention that this condition is a fixed value (mandatory).
    So, how can we make a Fixed Value (Calculation type) for a header condition to be distributed among the line items based on the base Value?
    Please revert back asap.
    Sure, points will be awarded for the same.

    as explained earlier ,
    system is distributes the header amount on the basic of value calculated by Basic X qty
    e.g.
    header value =100
    two line item
    1 is with Rs 4/- and qty is 10
    2 is with Rs 10/- and qty is 15
    so distribution is
    Rs 21.05/-  for 1st item
    and
    Rs 78.94/- for 2ed item
    regards,
    sujit

  • Setting the series color of a bi beans graph based on the data values

    How do I conditionally set the series color of a bi beans graph based on the data values?
    I am using the following code to get the data values and set the series color:
    Graph gr=(Graph)CmdrDashboardP1_pres1.getView();
    DataAccess da=gr.getGraphModel().getDataAccess();
    DataDirector dd=gr.getDataDirector();
    DataMap dm=dd.getDataMap();
    int re=dd.ROW_EDGE;
    int ce=dd.COLUMN_EDGE;
    Object val=da.getValue(re,ce,dm.DATA_TYPE);
    int seriesCount=da.getEdgeCurrentSlice(DataDirector.ROW_EDGE);
    if (val <=45.0)
    gr.getSeries().setColor(new Color(255,0,0),seriesCount);
    I get a NullPointerException from the line of code "Object val=da.getValue(re,ce,dm.DATA_TYPE)." I have tried the code with DATA_UNFORMATTED as well, but get the same exception. When I print the DataMap value of dm the results are [dataUnformatted, dataViewFormat, value, dataIsTotal, dataType].
    Also, I get the error "method <= (java.lang.Object,double) not found in class _CmdrDashboardP1" from the "if (val <=45.0)" code.
    Thanks for any assistance

    How do I conditionally set the series color of a bi beans graph based on the data values?
    I am using the following code to get the data values and set the series color:
    Graph gr=(Graph)CmdrDashboardP1_pres1.getView();
    DataAccess da=gr.getGraphModel().getDataAccess();
    DataDirector dd=gr.getDataDirector();
    DataMap dm=dd.getDataMap();
    int re=dd.ROW_EDGE;
    int ce=dd.COLUMN_EDGE;
    Object val=da.getValue(re,ce,dm.DATA_TYPE);
    int seriesCount=da.getEdgeCurrentSlice(DataDirector.ROW_EDGE);
    if (val <=45.0)
    gr.getSeries().setColor(new Color(255,0,0),seriesCount);
    I get a NullPointerException from the line of code "Object val=da.getValue(re,ce,dm.DATA_TYPE)." I have tried the code with DATA_UNFORMATTED as well, but get the same exception. When I print the DataMap value of dm the results are [dataUnformatted, dataViewFormat, value, dataIsTotal, dataType].
    Also, I get the error "method <= (java.lang.Object,double) not found in class _CmdrDashboardP1" from the "if (val <=45.0)" code.
    Thanks for any assistance

  • How to increase the salary based on the percentage value

    Hi All,
    Could you please let me know which API need to be used to implement the hike in salary based on the percentage value. And what all the parameters to be used.
    Appreciate your help...
    Thanks...

    Dear All,
    Any luck on this please?
    thanks..

  • Using Shading Dictionary to perform shading in pdf,before that the shading dictionary call from Pattern Dictionary.In the Pattern Dictionary there is an Matrix based on the matrix value  location the shading operatihow the axial shading is preserve in pdf

    using Shading Dictionary to perform shading in pdf,before that the shading dictionary call from Pattern Dictionary.In the Pattern Dictionary there is an Matrix based on the matrix value  location the shading operation is perform,So i dont know how to calculate value of pattern Dictionary matrix value.
    10 0 obj
    << /Type /Pattern
    /PatternType 2
    /Shading 11 0 R
    /Matrix [1.00 .00 .00 1.00 54.00 53.00]  // the matrix value how to calculate
    >>
    11 0 obj
    <<
    /ColorSpace /DeviceRGB
    /Function 12 0 R
    /ShadingType 2
    /Coords [109.2726 69.00 109.2726 .00]
    /Extend [true true]
    >>
    12 0 obj
    <<
    /FunctionType 0
    /Domain [.00 1.00]
    /Range [.00 1.00 .00 1.00 .00 1.00]
    /Size [1002]
    /BitsPerSample 8
    /Length 3006
    >>
    stream
    here is an stream of colors
    endstream
    endobj
    Can anybody help me please.
    Regards, Sasi kumar sekar.

    Hi, Sasi -
    The Matrix maps coordinates in your shading dictionary into User Space. That is, the Matrix entry in the Pattern dictionary specifies a coordinate transformation that will be applied to coordinates specified in the shading dictionary.
    To take your example, you have an axial shading extending from (rounding off) 109,69 to 109,0.  Your Pattern dictionary specifies the Matrix
    [ 1  0  0  1  54  53 ]
    This transformation matrix corresponds to a scale of 1,1 (that is, no change in scale) and a translation of 54,53. Thus, the actual endpoints for the axial shading will be the User Space positions 163,122 and 163,53 (assuming I’ve added correctly).
    As to what values to use for your Matrix, it depends on how you’ve set up your Shading dictionary. If the coordinates you’ve specified are actually where you want the gradient to go, then just use an identity matrix
    [ 1  0  0  1  0  0 ]
    By the way, are you sure that the Pattern dictionary includes a Matrix entry? I seem to remember (it's been a while since I've looked at Patterns) that the matrix is supplied as an argument to the makepattern operator:
    <<patternDict>> [ 1 0 0 1 0 0 ] makepattern
    Hope that helps.
    - John Deubert
      Acumen Training
      PostScript and PDF
      Training & Consulting

  • How to find bpel instance in 11g based on the index values

    We have 10g BPEL process where we define 4 index values for all the instances. Whenever support request comes, we ask index values and based on that we search the process instance.
    We have migrated this 10g bpel process to 11g now. How to find bpel instance in 11g based on the index values ???

    I have multiple bpel in my composite. I checked in ci_indexes table and it shows the instance number of the bpel process. But the em console is showing only the composite instance number. when I opened composite instance, I could see all the bpel process with instance number in the audit trail. How can I find the the actual composite instance number that I should search for in the em console ???

  • How to handle vendor discounts based on the qty / value procured.

    Hello
           How to handle vendor discounts based on the qty / value procured.
    a.       Scenario: you have entered into a contract with vendor that you will buy goods worth Rs 10000/- and if you buy goods worth more than 100000 the vendor says he will give a discount of Rs 5000/- @ the end of the year.  
    i)                    How to handle this sceneriou2019s with SAu2019s
    ii)                   What does STD SAP offer.
    Regards
    Sapman man

    Hi,
    For the discucount condition type, you have to maintain scales.
    Take Condition type -  Discount Value ( RB00)
    Discount Value ( RB00) - Means Fixed discount. For this condition type, you have to maintain Scale basis as Value scale 'B' in the condition type customization.
    Transcation : M/06
    Select your condition type RB00 and click on the details icon.
    In the Scales block, you have to maintain and save.Calculation type = Fixed amount
    Scale basis = Value scale 'B'
    For this condition type, you have to maintain scales in the inforecord.
    Transcation : ME12
    Select this condition type, click on the Scales icon. There you have to maintain like
    From : 10,0000            Rate: 5000.
    It means, if the document value is reached 10,0000 then discount is 5000rs. If the value islessthen the 10,0000 then no discount.
    Regards
    KRK

Maybe you are looking for

  • I have recently upgraded my firmware to ios 5 on my iphone 3gs and now i cant access my photos from my computer

    i have recently upgraded my my iphone 3gs to ios 5.0.1 and now my computer doesnt recognise it as a camera. is there any way i can access my photos stored on my phone from my computer? i also dont have wifi so i cant use the icloud option.

  • ITunes will not open because Quicktime!help!

    I clicked on the iTunes icon on my computer and a message pops up saying "Quick time is required to run iTunes.Please reinstall iTunes" and all u can do is press ok! how can i open my itunes???

  • Won't open website

    Why if Firefox is set as my default browser, when I click on an icon it opens the "print" dialog box instead of opening the site?

  • Webserver too slow

    Hi. I´ve a problem with the Webserver.I used the Web Publishing Tool to create a html file View Mode Embedded. My VI read data from RS-232 port every 2 seconds. The problem is: When the HOST has control of the VI, the webpage in the CLIENT does not r

  • Inconsistent Integration Scenario Modeling behaviour

    Hi folks, In order to created an Integration Scenario, i defined Application Component Views in three swim lanes. Created 4 actions and established connections between them. Scenario is working fine. But after some time, in display mode of scenario.