Determination of the value of column based on previous records

Hello

I have this table. Please just exclude the Prev_Equal column for my original table.
+---------+--------+---------+---------+------------+
| info_id | fruit  | Qty In  | Qty Out | Prev_Equal |
+---------+--------+---------+---------+------------+
|       1 | apple  |      10 |       7 |         No |
|       2 | apple  |      10 |      10 |         No |
|       3 | apple  |      10 |       8 |        Yes |
|       4 | orange |      20 |      18 |         No |
|       5 | orange |      20 |      20 |         No |
|       6 | orange |      20 |      17 |        Yes |
|       7 | orange |      20 |      20 |        Yes |
|       8 | orange |      20 |       1 |        Yes |
|       9 | grape  |      15 |      15 |         No |
|      10 | grape  |      15 |      15 |        Yes |
+---------+--------+---------+---------+------------+
For the table of Prev_Equal, it is marked as being:
No: if it's the first item or there is no history that has quantity = QTY OUT
Otherwise Yes

How do I do this in Oracle SQL?

Thanks in advance

Hello

Claude2005 wrote:
... For the table of Prev_Equal, it is marked as being:
No: if it's the first item

I assume you mean the first element in order of info_id for a given value of fruits.

or there is no history that has quantity = QTY OUT
Otherwise Yes

How do I do this in Oracle SQL?

LAG can only watch a specific previous line; This is why the above fails on the line where info_id = 7. We need a function that can examine all the previous lines, like this:

SELECT       t.*
,       NVL ( MAX ( CASE
                     WHEN  qty_in = qty_out
                       THEN  'Yes'
                     END
              ) OVER ( PARTITION BY  fruit
                           ORDER BY        info_id
                           ROWS BETWEEN  UNBOUNDED PRECEDING
                       AND        1          PRECEDING
                       )
           , 'No'
           )          AS prev_equal
FROM       t
ORDER BY  info_id
;

Tags: Database

Similar Questions

  • Add the value of column based on a different line with the same id

    Hello world

    I have a query that displays the first three columns of the table below. I would like to add a column to this output, most indicating (for each row) if there is an electronic product in the same order. For example, the command 1 in the table below contains 1 unit of furniture and 1 unit of electronics. In my outings, I would add a flag 'Y' for the two rows 1 and 3. Also, I would add a "N" indicator to any order which does contain all the electronics.

    Any ideas on how to achieve this? Any idea or suggestion is appreciated!

    order_id product_cat quantity with_electronics
    1furniture1THERE
    2grocery1N
    1Electronics1THERE

    Thank you

    Zsolt

    Hi, Zsolt,

    You can also use analytical functions.  For example:

    SELECT order_id, product_cat, quantity

    MAX (CASE

    WHEN product_cat = 'electronics '.

    THEN 'Y '.

    ANOTHER "N".

    END

    ) OVER (PARTITION BY order_id) AS with_electronics

    Orders

    ;

    Of course, I can't test it without a table.

  • change the color of line based on the value of column 5 Apex in the classic report

    Version of the apex 5.0.0.00.31

    Standard universal theme

    Page theme default template

    Classic report

    Foldable report template

    Hello

    I know this question has been asked several times here, but I'm working on 5 Apex and need to know the correct way to do it in this version.

    I need to change the color of the text of the entire line (no background color) based on the value in one of the columns of the classic report. I have just two conditions, if the value of column = Yes, color should be red, otherwise it must be green.

    I am new to jscript and css, so appreciate if someone can tell me the solution with steps.

    I have already checked this link that changes the value of the column, need to do something similar to the whole line.

    https://tylermuth.WordPress.com/2007/12/01/conditional-column-formatting-in-apex/

    Hi coolmaddy007-Oracle,.

    Here's an example set up on the apex.oracle.com according to the specifications you gave: https://apex.oracle.com/pls/apex/f?p=35467:1

    Version of the apex 5.0.0.00.31

    Standard universal theme

    Page theme default template

    Classic report

    Foldable report template

    Here is how it is done:

    Create a dynamic action with the following specifications:

    Name: Give the appropriate name

    Event: After refresh

    Selection type: region

    Region: select your region classic report

    Condition: No strings attached

    Action: Run the JavaScript Code

    Fire on loading the Page: Yes

    Code:

    $('td[headers="JOB"]').each(function() {
      if ( $(this).text() === 'MANAGER' ) {
        $(this).closest('tr').find('td').css({"color":"red"});
      }
      if ( $(this).text() === 'SALESMAN' ) {
        $(this).closest('tr').find('td').css({"color":"green"});
      }
      if ( $(this).text() === 'CLERK' ) {
        $(this).closest('tr').find('td').css({"color":"blue"});
      }
    });
    

    NOTE: Download the selector appropriate for your knowledge $('td[headers="JOB"]') case using firebug/browser development tools.

    Items concerned: leave blank.

    PS: Changed the example to change the color of text instead of the background color.

    I hope this helps!

    Kind regards

    Kiran

  • Hi, I recently bought numbers in order to create a commercial newspaper. I'm the pen and paper. I need help to create a formula. A purchase column determines if the entry price column is subtracted from the price of output column or output subtracted

    Hi, I recently bought numbers in order to create a commercial newspaper. I'm the pen and paper. I need help to create a formula. A purchase column; Determines if the entry price column is subtracted from the price of output column (buy) or subtracted from (Sell) entry exit. Thank you for your help

    Hi B',.

    Buying and selling in column B

    Price of entry in column c.

    Exit in column D price

    Formula (and outcome) in column E

    If the column will B always contained 'Buy' or 'Sell', it works. It is default to a calculation of 'sell' if sale or has been specified.

    E2: = IF (B = "Buy", D - C, C - D)

    If you want to delay the calculation until the amounts entered in C and D, use this version:

    E2: = IF (OR (LEN (C) < 1, LEN (D) < 1,"", IF (B = "Buy", D - C, C - D) ")

    If you want to delay the calculation until all three ducks are on a line (B contains buy or sell, C and D contain both data), use this version:

    E2: = IF (OR (LEN (C) < 1, LEN (D) < 1,"", IF (B = "Buy", D - C, IF(B="Sell",C-D,) "" ")))

    Third version used in this table.

    Kind regards

    Barry

  • Request to remove row where the value of column contains alphabets

    Hello

    Could someone please help me to get this application working.

    Request to remove row where the value of column contains alphabets.

    DELETE FROM BIN_ITEM WHERE order_nmb LIKE '% [A - Z] % ' | LIKE '% [a - z] %'

    Thank you and best regards,

    Madam.

    SELECT order_nmb FROM BIN_ITEM WHERE regexp_count(order_nmb,'[0-9]') = 0

    ----

    Ramin Hashimzade

  • sort the month name column based on id in RPD itself only months

    sort the month name column based on id months in RPD itself only without creating the logical column.

    Set your id for months as the column sort order of the name of the month.

    Double click on the month name-> in general tab set the column sort order as the id of the month

  • How to get the values separated by commas of multiple records in table

    How to get the values separated by commas of multiple records in table

    for example

    name address age sex
    a 12 m e
    b hh 12 f
    BB c 13 h

    I need to get output as a, b, c from a query

    Use the query as below he works for me, change the names of tables and columns

    SELECT SUBSTR (SYS_CONNECT_BY_PATH (PROXY_EMAIL, ','), 2) csv FROM (SELECT PROXY_EMAIL, ROW_NUMBER () ON the rn (ORDER OF PROXY_EMAIL), COUNT (*) NTC (STARS_PROXY_ASSIGNMENT) WHERE EMPLID = #EMPLID) WHERE rn = cnt START WITH rn = 1 CONNECT BY rn = rn + 1 ADVANCE

  • How to extract the values of column aliases based on different column values?

    Hello gurus,

    I have a table with the following struture-
    "drop table T;
    create table T(Name, Symbol, Amount,dep) as select
    'Anderia', 'AA', 1050000,'HR' from dual union all select
    'Michael', 'ML',150000,'Sales' from DUAL union all select
    'Bill', 'BL', 1050000,'Finance' from dual union all select
    'Nancy', 'NY', 4000,'HR' from DUAL union all select
    'Anderia', 'AA',3000,'HR' from dual union all select
    'Michael', 'ML',1050000,'Sales' from DUAL union all select
    'Bill', 'BL', 1200000,'Finance' from DUAL union all select
    'Anderia', 'AA', 1200000,'HR' from DUAL union all select
    'Vish', 'VH', 1200000,'Marketing' from DUAL;"
    And try to find the values of the column as
    Name, symbol, dep, amount, % Total, Total $Cumm, rank but some additional as-columns

    Amount HR, % HRTotal, $HR Cumm Total,
    Finance amount, FinanceTotal %, $Finance Cumm Total
    Sales amount, a percentage of Total sales, $Sales Cumm Total.
    Amount marketing, MarketingTotal %, $Marketing Cumm Total

    then I use the following query to retrieve the name, the symbol, the dep, amount, % Total, Total $Cumm, rank columns.
    select name
         , decode(grouping(symbol), 0, symbol, 'Total') symbol
         , dep
         , sum(amount) amount
         , sum(per_total) "% Total"
         , decode(grouping(symbol), 0, max(Cum_per_total), null) "% Cumm Total"
         , decode(grouping(symbol), 0, max(rank), null) rank
      from (
              select name
                   , symbol
                , dep
                   , amount
                   , per_total 
                   , sum(per_total) over(order by rk) cum_per_total
                   , rank
                   , rk
                from (     
                        select name
                             , symbol
                    , dep
                             , sum(amount) amount
                             , round((sum(amount)/max(total_amount)) * 100,2) per_total
                             , dense_rank () over (order by sum(amount) desc) as rank
                             , row_number() over(order by sum(amount) desc) as rk
                          from (
                                 select name
                                      , symbol
                                      , amount
                          , dep
                                      , sum(amount) over() total_amount 
                                      , sum(amount) over () 
                                   from t
                               )
                         group 
                            by name, symbol, dep
                    )
            )
      group         
         by grouping sets((name, symbol, dep), ())
      order by rank, max(rk) nulls last
    But I want to extract the following columns so... How can I do?

    Amount HR, % HRTotal, $HR Cumm Total,
    Finance amount, FinanceTotal %, $Finance Cumm Total
    Sales amount, a percentage of Total sales, $Sales Cumm Total.
    Amount marketing, MarketingTotal %, $Marketing Cumm Total


    as I want that all records, then will the dep..do-specific I need to use the case here?
    Thanks for all your time and effort in advance

    If I understand your needs, you need pivot: SQL and PL/SQL FAQ

  • Retrieves the values of XML based on filters

    I am new to use XML with oracle. This is a sample XML from an XML file, now the question is it really possible to write sql queries to extract based on a result, that is to say, if I do a clip like this extract(column_name,//Requests//RequestBody//Item//ItemHeader//ItemAction/text(),).getStringVal () then I results XL1XL2 what I need exactly is only "ItemAction" XML member value when the value is = 'Add '. which means that the final result value, I need XL1. Please note that the values I gave ablove XL1 and XL2, is flexible, that is, sometimes, it's XLLL1 some time XL1, so can't go based on the use of SUBSTR function to extract a fixed value.

    < ns3:Requests >

    < ns3:Request >

    < ns3:RequestBody >

    < ns3:Item >

    < ns3:ItemHeader >

    < ns3:ItemId > 99 < / ns3:ItemId >

    < ns3:ItemType > TypItem < / ns3:ItemType >

    < ns3:ItemAction > Add < / ns3:ItemAction >

    < / ns3:ItemHeader >

    < ns3:ItemBody >

    < ns3:ServiceItem >

    < ns3:ServiceCode > XL1 < / ns3:ServiceCode >

    < / ns3:ServiceItem >

    < / ns3:ItemBody >

    < / ns3:Item >

    < ns3:Item >

    < ns3:ItemHeader >

    < ns3:ItemId > 100 < / ns3:ItemId >

    < ns3:ItemType > TypItem < / ns3:ItemType >

    < ns3:ItemAction > Remove < / ns3:ItemAction >

    < / ns3:ItemHeader >

    < ns3:ItemBody >

    < ns3:ServiceItem >

    < ns3:ServiceCode > XL2 < / ns3:ServiceCode >

    < / ns3:ServiceItem >

    < / ns3:ItemBody >

    < / ns3:Item >

    < / ns3:RequestBody >

    < / ns3:Request >

    < / ns3:Requests >

    As I understand it, you want to return the code of service elements where the ItemHeader = "add"?  Note: You have missed your name space in the XML document, so I added a.

    with data (the_xml) as)

    Select xmltype (')

    99

    TypItem

    Add

    XL1

    100

    TypItem

    Delete

    XL2

    ')

    of the double

    )

    Select x.*

    data d

    Join the xmltable (xmlnamespaces ('somenamespace "like" ns3 "),)

    "' ns3:Requests / ns3:Request / / ns3:RequestBody / / ns3:Item [ns3:ItemHeader / ns3:ItemAction ="Add"]"

    in passing d.the_xml

    columns

    Path of varchar2 (20) conduitePlan ' ns3:ItemBody / ns3:ServiceItem / ns3:ServiceCode'

    ) x 1 = 1

    RESULT

    CONDUITEPLAN

    'XL1 '.

  • Problems with slot-shaped table and set the values of column

    Hello

    I have a problem with a tabular presentation.

    I have two tables

    P_detail and table v_master

    columns of v_master:
    v_id
    v_Name
    v_info

    columns of p_detail:
    P_ID
    p_master_fk
    p_name
    p_info

    I want to have a tabular presentation where I can store permanent data retail values. That's why I want to keep the default main column join the detail columns.
    In SQL, I can do this with an outer join:

    SELECT m.v_name, d.p_master_fk, d.p_name, d.p_info
    OF v_master, p_detail
    WHERE v_id = p_master_fk (+)

    I get the lines that exist for the master data and can add values for the columns of detail. I removed the "add lines" because that makes no sense, because the amount lines are already offered at the opening of the tabular presentation.

    Now, I want to get/save the v_id (main table) in the p_master_fk column value

    How can I do this?

    Thank you and best regards,
    Matthias

    Hello

    One approach is to use a database instead trigger. If you define a database view using the query:

    SELECT m.v_id, m.v_name, d.p_id, d.p_master_fk, d.p_name, d.p_info
    OF v_master m, p_detail d
    WHERE v_id = p_master_fk (+)

    Then, create a trigger on the view that will insert in the detail table if d.p_id is null and update the secondary table if d.p_id is not null instead.

    The Apex tabular form is then based on the view (with identifiers like hidden columns) and all treatments multirow Apex should work without modification.

    Rod West

  • Returns the value of column line

    Greetings!  I currently have a request we will tell

    SELECT value, period FROM MAS_CFUS_KEYACM_CONTROLDATA ORDER BY cf_keyword_ID

    RESULTS

    Period value

    --------------------------

    100.0002 1 JANUARY 14

    -35.68 1 DECEMBER 14

    -1943.67 NOVEMBER 1, 14

    678.0013 OCTOBER 1, 14

    This continues for about 15 results by cf_keyword_ID.

    I'm looking to return the VALUE first in a new column called PREV1, the second value of PREV2, third in PREV3 and so on.  The same goes for the dates.  And all this for only the first 10 values of each cf_keyword_ID.  Can anyone suggest the best way to achieve this?

    Thank you!!

    Hello

    This is called pivoting.  Because I don't have a copy of your table test, I'll use scott.emp to illustrate.

    This shows the first 3 employees for each job, in order by hiredate, along with their hiredates:

    WITH relevant_data AS

    (

    SELECT ename, job, hiredate

    row_number () taken OVER (PARTITION OF work

    ORDER BY hiredate

    ) AS r_num

    FROM scott.emp

    )

    SELECT *.

    OF relevant_data

    PIVOT (MIN (ename) AS ename

    MIN (hiredate) AS hiredate

    FOR r_num (1, 2, 3)

    )

    ORDER BY job

    ;

    Output:

    WORK 1_ENAME 1_HIREDATE 2_ENAME 2_HIREDATE 3_ENAME 3_HIREDATE

    --------- ---------- ----------- ---------- ----------- ---------- -----------

    ANALYST FORD 3 December 1981 SCOTT April 19, 1987

    The CLERK SMITH December 17, 1980, 3 December 1981 JAMES MILLER January 23, 1982

    MANAGER JONES 2 April 1981 BLAKE 1 May 1981 CLARK June 9, 1981

    PRESIDENT KING November 17, 1981

    SELLER ALLEN 20 February 1981 WARD 22 February 1981 TURNER 08-Sep-1981

    There are actually more than 3 SECRETARIES and SALESMEN.  Which does not cause an error; the only first 3 are shown.

    As you can see, having less of 3 does not cause any errors, either.

    For more info on pivots, see the FAQ of the Forum:

    Re: 4. How can I convert rows to columns?

    I hope that answers your question.

    If this isn't the case, please post a small example of data (CREATE TABLE and only relevant columns, INSERT statements) for all of the tables involved and also publish outcomes from these data.

    Explain, using specific examples, how you get these results from these data.

    If yod post rather a problem using scott.emp, then you need not display the sample data; just results and explanations.

    Always say what version of Oracle you are using (for example, 11.2.0.2.0).

    See the FAQ forum:

    Re: 2. How can I ask a question in the forums?

  • "All the values in column" change in the dash prompt

    In OBIEE 11 g, how to change the dashboard prompt label everything value? I don't want to change the value in the XML file, because it will prompt value impact all the dashboard.
    This is there best method to implement this problem?

    For example:
    In prompt dashboard-> edit-> options-> check ' include "All values in the column" in the list ", so I can display value"(toutes les valeurs de colonne) ' in the command prompt. " Customers want to change this value, such as 'all values '. Is this possible? Thank you.

    Hello

    Can do this by using Union All is prompt, SQL and variable presentation in the report.

    Reference: http://www.varanasisaichand.com/2010/01/editing-all-choices-in-dashboard.html

    Kind regards
    Srikanth

  • ADF: Assigning the value of column VO to OutputText.

    Hi all

    I have a VO who im showing as ADF read Table only. And one column that VO should be included outside of this table, I mean, I don't want to include this column in the table that I want to assign the value of the column to Text output component (Active).
    I want to assign the value of the column to the output text component.
    How can I achieve this.
    I think im clear with my requirement.

    Any answer will be really grateful.

    Please read this before posting
    https://forums.Oracle.com/forums/Ann.jspa?annID=56

    am now back to the topic.

    tell as an example.
    Here, I had to employee vo drag and drop as readonly af:table employee.
    in this readonly af:table no need to show their id of employee, but you don't want to show this id used as some text output at the top / bottom of the table.
    I think reason?. as it comes to your condition.

    If am so right, moving later.
    Drag and drop the af: table without employee id. and then drag and drop the employee as af text id: output
    important: employee select id in the user interface that came out text go to partial property inspector trigger are at table.

    You may wonder why I like this mean?
    If you like this then means that move through the records of documents / select in af:table means revalent employee id get you. This way you get the desired results. :)

    Thanks & cordially
    ADF7.

  • How can I compare the value of column within the COUNT() function?

    I want to compare the value of the column within the COUNT() function as below how ever it gives me the error. I want to calculate the percentage, how can I do this task?
    Thank you.


    SELECT department_id
    , COUNTY (salary < 250000) / COUNT (*)
    OF plch_employees
    GROUP BY department_id
    ORDER BY department_id;
    SELECT  department_id.
            COUNT(CASE WHEN salary < 250000 THEN 1 END) / COUNT(*)
      FROM  plch_employees
      GROUP BY department_id
      ORDER BY department_id
    /
    

    SY.

  • Clear the check box according to the value of column DB

    Hello
    My requirement is to disable the check box according to the value of a column DB. Say for example my report displays the following. Check box, the name of the EMP, Dept. If the Department is the checkbox should be disabled and user should not be able to select the check box.
    Ask your help for a solution.
    Thank you
    Prasanth

    You must use the parameter p_attributes of the apex_item.checkbox API to make the boxes off (readonly do not work with the checkboxes)

    SELECT ..
    CASE WHEN  THEN APEX_ITEM.CHECKBOX(1,)
                         ELSE APEX_ITEM.CHECKBOX(1,,'disabled="disabled"')
              END 
      ..
    

Maybe you are looking for