Compare two results from the same table

i have two results from the same table that i would like to compare. below is my query and the results i want to compare
SELECT tblItemRoutingBOM.ItemRevID, tblItem.ItemID, tblItem.PartNum, tblItem.ItemName, tblItem.ManufacturerPartNum AS [Mfg Part#], tblItemRoutingBOM.Quantity
FROM tblItemRouting
INNER JOIN tblItemRoutingBOM ON tblItemRouting.ItemRoutingID = tblItemRoutingBOM.ItemRoutingID
INNER JOIN tblItem ON tblItemRoutingBOM.ItemID = tblItem.ItemID
WHERE tblItemRoutingBOM.ItemRevID in (61,70)
as you can see i am returning two records using the where clause
ItemRevID, ItemID, PartNum, ItemName, Manufacturer, Mfg Part#, Quantity
61,121,331503,.233 Aluminum Sheet,,1
70,121,331503,.233 Aluminum Sheet,,3
now what i am looking for is to combine these two together into one row with the following added.  two columns for each QTY, QTY1 = 1 and QTY2 = 3 with a third column added that is the difference between the two QTY Diff = 2
Any thoughts?

Here are the two statements that i want to combine, results for each are attached
SELECT tblItem.ItemID, Sum(tblItemRoutingBOM.Quantity) AS SumOfQuantity, tblItem.PartNum AS [Part #],
tblItem.ItemName, tblManufacturer.ManufacturerName AS Manufacturer, tblItem.ManufacturerPartNum AS [Mfg Part#]
FROM tblItemRouting
INNER JOIN tblItemRoutingBOM ON tblItemRouting.ItemRoutingID = tblItemRoutingBOM.ItemRoutingID
INNER JOIN tblItem ON tblItemRoutingBOM.ItemID = tblItem.ItemID
INNER JOIN tblUnits ON tblItem.UnitID = tblUnits.UnitID
LEFT JOIN tblManufacturer ON tblItem.ManufacturerID = tblManufacturer.ManufacturerID
WHERE tblItemRoutingBOM.ItemRevID=61
GROUP BY tblItem.ItemID,tblItem.PartNum,tblItem.ItemName,tblManufacturer.ManufacturerName,tblItem.ManufacturerPartNum
SELECT tblItem.ItemID, Sum(tblItemRoutingBOM.Quantity) AS Quantity, tblItem.PartNum AS [Part #],
tblItem.ItemName, tblManufacturer.ManufacturerName AS Manufacturer, tblItem.ManufacturerPartNum AS [Mfg Part#]
FROM tblItemRouting
INNER JOIN tblItemRoutingBOM ON tblItemRouting.ItemRoutingID = tblItemRoutingBOM.ItemRoutingID
INNER JOIN tblItem ON tblItemRoutingBOM.ItemID = tblItem.ItemID
INNER JOIN tblUnits ON tblItem.UnitID = tblUnits.UnitID
LEFT JOIN tblManufacturer ON tblItem.ManufacturerID = tblManufacturer.ManufacturerID
WHERE tblItemRoutingBOM.ItemRevID=70
GROUP BY tblItem.ItemID,tblItem.PartNum,tblItem.ItemName,tblManufacturer.ManufacturerName,tblItem.ManufacturerPartNum
114,11,55002,Pepsi Blue Cap,NULL,
117,5,331501,Marigold Yellow For ABS,NULL,
121,1,331503,.233 Aluminum Sheet,NULL,
125,2,331504,Velvet Vinyl .008,NULL,
114,33,55002,Pepsi Blue Cap,NULL,
117,15,331501,Marigold Yellow For ABS,NULL,
121,3,331503,.233 Aluminum Sheet,NULL,
125,6,331504,Velvet Vinyl .008,NULL,
my returned result should combine above with two extra columns (two extra columns because i have two results to combine)
114, 11, 33, 22, 55002, Pepsi Blue Cap, NULL,
117, 5, 15, 10, 331501, Marigold Yellow For ABS, NULL
121,1, 3, 2, 331503, .233 Aluminum Sheet, NULL
125, 2, 6, 4, 331504, Velvet Vinyl .008, NULL
Columns go as such, ID, QTY1 (for 61), QTY2 (for 70), Diff (QTY1-QTY2), PartNum, ItemName, Mfg, Mfg Part#
IF the results from one of those two are empty then i would see something like this
114, 11, 0, 11, 55002, Pepsi Blue Cap, NULL,
117, 5, 0, 5, 331501, Marigold Yellow For ABS, NULL
121,1, 0, 1, 331503, .233 Aluminum Sheet, NULL
125, 2, 0, 2, 331504, Velvet Vinyl .008, NULL

Similar Messages

  • How to compare two fields from the same table in the select statement

    Hi, friends
    I try to compare tow fields from the same table, but no result,
    For example, this
    data: cptotchek tyep i.
    select count(*) into cptotchek
    from aufk where erdat = aufk-idat2 .
    The result is  cptotchek = 0, but there are the records in aufk , where,  aufk-erdat = aufk-idat2.
    Please, help me, i don't use the loop statement for optimize my program.
    Regards

    Hi  ,
           it will not return  any value   when you are using   column of same table 
           such as Date Field   , Because  while Using Aggregate Function  it will not check with self column
    .      For that you have to take data in one internal table and then you can work on it  .
         And if you are worried about Performance  it will not affect  , untill you are selecting only required data  .
    you can try this way  .
    data: cptotchek type i.
    types : begin of  w_aufk.
            include structure aufk  .
          types : end of  w_aufk .
    data : it_aufk type standard table of w_aufk with header line  .
    select * into corresponding fields of table it_aufk
    from aufk  .
    loop at it_aufk .
    if it_aufk-erdat  = it_aufk-idat2 .
    write : / it_aufk-erdat , it_aufk-idat2 .
    else .
    delete it_aufk .
    endif  .
    endloop.
    Regards
    Deepak.

  • Compare two members from the same dimension in HFR

    Hi,
    Is it possibe to compare two members from the same dimension in HFR? The requirement is to compare Year and Week members from the same dimension. The Week date will be selected from POV. The corresponding Year date should be displayed in the report. Week dates are in the format W2008-03-07 and Year dates are in YTD2008-03-07.
    The dates are same except the preceding character.I am unable to compare these two. In my understanding there's no substring or replace functions in HFR.
    Kindly help. Thanks in advance.
    Regards,
    Uma

    Hi,
    How is your database structured? it may be possible to use the 'RelativeMember' function if it will always be the same number of steps between the 'W' member and the 'YTD' member, e.g. if your hierarchy is something like:
    Time
    .Weeks
    ..W2008-03-07
    ..W2008-03-10 etc.. for 52 weeks
    .YTD
    ..YTD2008-03-07
    ..YTD2008-03-10 etc.. for 52 weeks
    In your report select 'Current Point of View for Time' in one row/column and in the other use:
    RelativeMember set up as follows:
    Member: Current Point of View for Time
    Offset: 52
    Hierarchy: Time
    RelativeMemberList: Lev0, Time
    UseFirstDescendant: leave unselected
    Hope this helps
    StuartGame
    www.analitica.co.uk

  • Calculating average time from two records from the same table.

    Hi all
    I need to calculate the average time between two events that are recorded in the same table.
    The table is TMS_MESSAGE_AUDIT_LOG
    MESSAGE_ID VARCHAR2(16 BYTE) NOT NULL,
    MESSAGE_VERSION NUMBER(2) NOT NULL,
    CREATE_TM VARCHAR2(18 BYTE) NOT NULL,
    MESSAGE_STATUS VARCHAR2(30 BYTE),
    TRANSACTION_TYPE_NM VARCHAR2(30 BYTE),
    MESSAGE_TP VARCHAR2(3 BYTE),
    WORKFLOW_OBJECT VARCHAR2(30 BYTE) NOT NULL,
    WORKFLOW_REQUEST VARCHAR2(30 BYTE) NOT NULL,
    WORKFLOW_RETURN_CD VARCHAR2(30 BYTE) NOT NULL,
    AUDIT_ACTION VARCHAR2(255 BYTE),
    LAST_UPDATE_USER_LOGON_ID VARCHAR2(12 BYTE),
    LOCAL_TM VARCHAR2(18 BYTE) NOT NULL,
    LOCAL_TIME_ZN_NM VARCHAR2(70 BYTE) NOT NULL,
    LOCAL_DAYLIGHT_IN CHAR(1 BYTE) NOT NULL,
    FPRINT VARCHAR2(30 BYTE)
    What i now need is
    When the MESSAGE_ID is the same i need have the average time between when the MESSAGE_STATUS is AA and BB ( I need the time out of the CREATE_TM field )
    And this for every 15 minutes interval.
    Because this table will become BIG millions and millions of records it needs to be fast.
    Can anybody help me.
    Marcel

    Something like this?
    CREATE TABLE wr_test
    ( message_id                 VARCHAR2(16 BYTE) NOT NULL
    , message_version            NUMBER(2) NOT NULL  -- Assumption: Acknowledged ver > Received ver
    , create_tm                  VARCHAR2(18 BYTE) NOT NULL
    , message_status             VARCHAR2(30 BYTE)
    , transaction_type_nm        VARCHAR2(30 BYTE)
    , workflow_object            VARCHAR2(30 BYTE) DEFAULT 'x' NOT NULL
    , workflow_request           VARCHAR2(30 BYTE) DEFAULT 'x' NOT NULL
    , workflow_return_cd         VARCHAR2(30 BYTE) DEFAULT 'x' NOT NULL
    , audit_action               VARCHAR2(255 BYTE)
    , last_update_user_logon_id  VARCHAR2(12 BYTE)
    , local_tm                   VARCHAR2(18 BYTE) NOT NULL
    , local_time_zn_nm           VARCHAR2(70 BYTE) DEFAULT 'GMT' NOT NULL
    , local_daylight_in          CHAR(1 BYTE) DEFAULT 'x' NOT NULL );
    INSERT ALL
    INTO   wr_test
           ( message_id
           , message_version
           , create_tm
           , message_status
           , local_tm )
    VALUES ( message_id
           , 1
           , create_tm
           , '(Receive)'
           , TO_CHAR(local_tm,'YYYYMMDD HH24:MI:SS') )
    INTO   wr_test
           ( message_id
           , message_version
           , create_tm
           , message_status
           , local_tm )
    VALUES ( message_id
           , 2
           , create_tm
           , 'Wait CLSB Ack'
         , TO_CHAR
           ( local_tm + NUMTODSINTERVAL(DBMS_RANDOM.VALUE(0,2e5),'SECOND')
           , 'YYYYMMDD HH24:MI:SS' ) )
    SELECT ROWNUM AS message_id
         , TO_CHAR(SYSDATE,'YYYYMMDD HH24:MI:SS') AS create_tm
         , DATE '2000-01-01' + DBMS_RANDOM.VALUE(0,3) AS local_tm
    FROM dual CONNECT BY ROWNUM < 100000;
    WITH src AS
         ( SELECT message_id
                , message_status
                , message_version
                , TO_DATE(SUBSTR(local_tm,1,17),'YYYYMMDD HH24:MI:SS') AS dt
                , TO_DATE(SUBSTR(local_tm,1,8),'YYYYMMDD') AS dt_day
                , TO_CHAR(TO_DATE(SUBSTR(local_tm,10,8),'HH24:MI:SS'),'SSSSS') AS dt_sec
           FROM   wr_test
           WHERE  message_status IN ('(Receive)','Wait CLSB Ack') )
    SELECT dt_day + NUMTODSINTERVAL(period,'SECOND') AS dt
         , NUMTODSINTERVAL(AVG(elapsed),'DAY') AS avg_elapsed
         , NUMTODSINTERVAL(MIN(elapsed),'DAY') AS min_elapsed
         , NUMTODSINTERVAL(MAX(elapsed),'DAY') AS max_elapsed
         , COUNT(*)
    FROM   ( SELECT message_id
                  , message_status
                  , dt_day
                  , TRUNC(dt_sec/300)*300 AS period
                  , LEAD(dt) OVER (PARTITION BY message_id ORDER BY message_version) AS ack_dt
                  , LEAD(dt) OVER (PARTITION BY message_id ORDER BY message_version) - dt AS elapsed
             FROM   src ) cal
    WHERE  cal.message_status = '(Receive)'
    GROUP BY dt_day, period
    ORDER BY 1;Replace "wr_test" with "tms_message_audit_log" in the WITH subquery to test on your data.

  • Two records from the same table in for loop

    I have a table that holds teams, a table that holds scores and a table that holds match data.
    I am finding it dificult to get the player data for the second team.
    Currently It is showing player information for one team.
    It does echo out the second team name, but not their player info.
    Can someone have a look at my code and make it work.
    I took off the code I had for the second team becuase it was ging me Error 1065
    Main Query:
    mysql_select_db($database_db, $db);
    $query_match_fixtures = "select m.match_id, date_format(m.date, '%d/%m/%Y') as mDate, m.time, t1.division, m.report, t1.team_name as team1_name, s1.score as score1, t2.team_name as team2_name, s2.score as score2
    from matches m left join (matchscores s1 left join team t1 on t1.team_id = s1.team) on (s1.match_id = m.match_id) left join (matchscores s2 left join team t2 on t2.team_id = s2.team) on (s2.match_id = m.match_id)
    where s1.team <> s2.team AND m.match_id = $matchID
    group by match_id
    order by m.match_id";
    $match_fixtures = mysql_query($query_match_fixtures, $db) or die(mysql_error());
    //$row_match_fixtures = mysql_fetch_assoc($match_fixtures);
    $totalRows_match_fixtures = mysql_num_rows($match_fixtures);
    Player extraction:
    mysql_select_db($database_db, $db);
    $row_match_player = array();
    for ($i = 0; $i < $totalRows_history; $i++)
        $row_history[$i] = mysql_fetch_assoc($history);
    for ($i = 0; $i < $totalRows_match_fixtures; $i++)
        $row_match_fixtures[$i] = mysql_fetch_assoc($match_fixtures);
        $match_player_query = "SELECT *
                               FROM match_player
                                LEFT JOIN player on player.player_id = match_player.player_id
                                LEFT JOIN team ON player.team_id = team.team_id
                               WHERE match_id = ".$matchID."
                                AND team.team_name = '".$row_match_fixtures[$i]['team1_name']."'";
        $result_match_player = mysql_query($match_player_query, $db) or die("large error ".mysql_errno());
        $totalRows_match_player = mysql_num_rows($result_match_player);
        for ($r; $r < $totalRows_match_player; $r++)
            $temp_row_match_player[$r] = mysql_fetch_assoc($result_match_player);
        array_push($row_match_player, $temp_row_match_player);
    The display table:
            <div class="tableHeading">
            <h2><?php echo $row_history['mDate']; ?></h2>
            </div>
            <table width="100%" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td height="25" bgcolor="#000000"><div align="left" style="color:#FFFFFF"><strong>Type</strong></div></td>
        <td height="25" bgcolor="#000000"><div align="left" style="color:#FFFFFF"><strong>Home</strong></div></td>
        <td height="25" bgcolor="#000000"><div align="center" style="color:#FFFFFF"><strong>Score</strong></div></td>
        <td height="25" bgcolor="#000000"><div align="center" style="color:#FFFFFF"><strong>Away</strong></div></td>
        <td height="25" bgcolor="#000000"><div align="center" style="color:#FFFFFF"><strong>Kick-Off</strong></div></td>
        <td height="25" bgcolor="#000000"><div align="center" style="color:#FFFFFF"><strong>Venue</strong></div></td>
        <td height="25" bgcolor="#000000"><div align="center" style="color:#FFFFFF"><strong>Referee</strong></div></td>
      </tr>
      <tr>
        <?php foreach ($row_match_fixtures as $show_match_fixtures)
        { ?>
            <td height="25" bgcolor="#dfdfdf">
            <div align="left"><?php echo $show_match_fixtures['division']; ?></div>
            </td>
            <td height="25" bgcolor="#dfdfdf">
            <div align="left"><?php echo $show_match_fixtures['team1_name']; ?></div>
            </td>
            <td height="25" bgcolor="#dfdfdf">
            <div align="center"><?php echo $show_match_fixtures['score1']; ?> - <?php echo $show_match_fixtures['score2']; ?></div>
            </td>
            <td height="25" bgcolor="#dfdfdf">
            <div align="center"><?php echo $show_match_fixtures['team2_name']; ?></div>
            </td>
            <td height="25" bgcolor="#dfdfdf">
            <!-- You do not want a nested loop inside the header so these results will have to go inside the table-->
            <div align="center"><?php echo $row_history['time']; ?></div>
            </td>
            <td height="25" bgcolor="#dfdfdf">
            <div align="center"><?php echo $row_history['venue_name']; ?></div>
            </td>
            <td height="25" bgcolor="#dfdfdf">
            <div align="center"><?php echo $row_history['fname']; ?> <?php echo $row_history['sname']; ?></div>
            </td>
        </tr>
          <tr>
            <?php foreach ($row_match_player as $player_array)
                   foreach ($player_array as $player_display)
            ?>
            <td valign="top">Goalscorers</td>     
            <td>
              <?php echo $player_display['fname']." ".$player_display['sname']." (".$player_display['Goals']; ?>)<br />
            </td>
            <td> </td>
            <td>
              <?php echo $player_display['fname']." ".$player_display['sname']." (".$player_display['Goals']; ?>)<br />
            </td>
            <td> </td>
            <td> </td>
            <td> </td>
          </tr>
          <tr>
            <td valign="top">Yellow Cards</td>
            <td><?php echo $player_display['YC']; ?></td>
            <td> </td>
            <td><?php echo $player_display['YC']; ?></td>
            <td> </td>
            <td> </td>
            <td> </td>
          </tr>
          <tr>
            <td valign="top">Red Cards</td>
            <td><?php echo $player_display['RC']; ?></td>
            <td> </td>
            <td><?php echo $player_display['RC']; ?></td>
            <td> </td>
            <td> </td>
            <td> </td>
          </tr>
          <tr>
            <td valign="top">Man of the Match</td>
            <td><?php echo $player_display['fname']; ?> <?php echo $player_display['sname']; ?></td>
            <td> </td>
            <td><?php echo $player_display['fname']; ?> <?php echo $player_display['sname']; ?></td>
            <td> </td>
            <td> </td>
            <td> </td>
          </tr>
                <?php
                    }// close and unset $player_display
                    unset($player_display);
                } //close and unset $player_array
            unset($player_array);
         } //close and unset $show_match_fixtures
        unset($show_match_fixtures);?>
    </table>
    As you can see from  the picture above the table is displayed with the name of the "goal  scorer" for that team under (home) or Home team
    When I try to create the same thing for away team I get a error, either a syntax error or 1065.
    I tried having a foreach do two queries but that did not work.
    Any help would be appriecated

    I did try that, but I have messed it up.
    Now the team names do not display at the top of the table.

  • Compare two rows in a same table

    Dear all
    I need to compare two rows in the same table, I dont know hoe to do it in pl/sql. Some one please help me on this.
    example:
    tr br price
    xya0001 ama7 12
    xya0003 ama6 14
    xya0004 ama7 16
    in the table tr is a unique value for each row, I need to compare price column and see whether the first value is less or greater than the next value and, if it is greater put the corresponding br value to a variable and if it is smaller put the corresponding br value to another variable. I dont know a method to do it, as I'm new to pl/sql. Some one please help me in this

    not sure what you intend to do as you have mentioned that "TR" is unique and you just want to compare each record with just the next record. Hope below query helps. The value "G" or "L" in flag would indicate if the current records price is greater than or less than the price in next record.
    select tr,br,price,col4, case when price> col4 then 'G'  when price< col4 then 'L' end flag from (
    select tr,br,price,lag(price,1,0) over(order by tr) col4 from testcomp
    )

  • SUM two ROWS in the SAME Table

    Hi,
    I have a problem with this issue. I want to sum two rows from the same table, but I don´t know how to do that. I tried to do it with CTE, but always I get the same error "Ambiguous". I would like to ask you, if there is other manner to get that
    data (sum two rows) and if it is possible to see examples about it.
    Thank you  in advance

    Hi Vaibhav,
     I leave you my scrip:
    USE Modelling
    GO
    --TABLE Aer_Lingus_Income_Statement
    IF OBJECT_ID('Aer_Lingus_Income_Statement') IS NOT NULL
    DROP TABLE Aer_Lingus_Income_Statement
    GO
    CREATE TABLE Aer_Lingus_Income_Statement
    ID [nvarchar](255) NOT NULL,
    Name_Account [nvarchar](255) NULL,
    Company [nvarchar](255) NULL,
    Level0_Account [nvarchar](255) NULL,
    Level1_Account [nvarchar](255) NULL,
    Level2_Account [nvarchar](255) NULL,
    Level3_Account [nvarchar](255) NULL,
    Level4_Account [nvarchar](255) NULL,
    Level5_Account [nvarchar](255) NULL,
    Level6_Account [nvarchar](255) NULL,
    Level7_Account [nvarchar](255) NULL,
    Level8_Account [nvarchar](255) NULL,
    Year_2006 decimal (15,2) null,
    Year_2007 decimal (15,2) null,
    Year_2008 decimal (15,2) null,
    Year_2009 decimal (15,2) null,
    Year_2010 decimal (15,2) null,
    Year_2011 decimal (15,2) null,
    Year_2012 decimal (15,2) null,
    Year_2013 decimal (15,2) null,
    GO
    ALTER TABLE Aer_Lingus_Income_Statement
    ADD CONSTRAINT PK_Aer_Lingus_Income_Statement PRIMARY KEY (ID)
    GO
    INSERT INTO Aer_Lingus_Income_Statement
    SELECT *
    FROM Aer_Lingus_data_Income
    IF OBJECT_ID('Aer_Lingus_Income_Statement_Historic') IS NOT NULL
    DROP VIEW Aer_Lingus_Income_Statement_Historic
    GO
    CREATE VIEW Aer_Lingus_Income_Statement_Historic
    as
    Select Level0_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Level0_Account ='Revenue'
    Group by Level0_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account= 'Passenger revenue' and Level0_Account ='Revenue'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account= 'Ancillary revenue' and Level0_Account ='Revenue'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account= 'Other revenue' and Level0_Account ='Revenue'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account= 'Cargo revenue' and Level0_Account ='Revenue'
    Group by Name_Account
    UNION ALL
    Select Level0_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Level0_Account ='Operating expenses'
    Group by Level0_Account
    UNION ALL
    Select Level1_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Level1_Account ='Staff costs' and Level0_Account ='Operating expenses'
    Group by Level1_Account
    UNION ALL
    Select Level1_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Level1_Account ='Depreciation, amortisation and impairment' and Level0_Account ='Operating expenses'
    Group by Level1_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='Aircraft operating lease costs' and Level0_Account ='Operating expenses'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='Fuel and oil costs' and Level0_Account ='Operating expenses'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='Maintenance expenses' and Level0_Account ='Operating expenses'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='Airport charges' and Level0_Account ='Operating expenses'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='En-route charges' and Level0_Account ='Operating expenses'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='Distribution costs' and Level0_Account ='Operating expenses'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='Ground operations, catering and other operating costs' and Level0_Account ='Operating expenses'
    Group by Name_Account
    UNION ALL
    Select Level1_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Level1_Account ='Other (gains)/losses - net' and Level0_Account ='Operating expenses'
    Group by Level1_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='Employee profit share' and Level0_Account ='Operating expenses'
    Group by Name_Account
    GO
    WITH sumasRevenue
    AS (
    SELECT Name_Account, ID
    , sum(Year_2006) AS Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    WHERE Level0_Account = 'Revenue'
    GROUP BY Name_Account, ID
    WITH ROLLUP
    , total
    AS (
    SELECT Y2006,Y2007 ,Y2008,Y2009 ,Y2010 ,Y2011 ,Y2012 ,Y2013
    FROM sumasRevenue
    WHERE Name_Account IS NULL
    sumasOperatingExpensive
    AS (
    SELECT Name_Account, ID
    , sum(Year_2006) AS Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    WHERE Level0_Account = 'Operating expenses'
    GROUP BY Name_Account, ID
    WITH ROLLUP
    , total1
    AS (
    SELECT Y2006,Y2007 ,Y2008,Y2009 ,Y2010 ,Y2011 ,Y2012 ,Y2013
    FROM sumasOperatingExpensive
    WHERE Name_Account IS NULL
    SELECT distinct ID , s.Name_Account,
    (s.Y2006* 1.0 - t.Y2006) AS [V2006] ,(s.Y2007* 1.0 -T.Y2007 ) as [V2007] , (s.Y2008* 1.0 /T.Y2008 ) as [V2008],(s.Y2009* 1.0 /T.Y2009 ) as [V2009],
    (s.Y2010* 1.0 /T.Y2010 ) as [V2010],(s.Y2011* 1.0 /T.Y2011 ) as [V2011],(s.Y2012* 1.0 /T.Y2012 ) as [V2012],(s.Y2013* 1.0 /T.Y2013 ) as [V2013]
    FROM sumasRevenue AS s , sumasOperatingExpensive AS t
    Where ID IS NOT NULL
    UNION ALL
    SELECT distinct ID,COALESCE(s.Name_Account,'NON CURRENT ASSETS') AS Name_Account ,
    sum (s.Y2006* 1.0 / t.Y2006) as V2006,sum (s.Y2007* 1.0 / t.Y2007) as V2007,sum (s.Y2008* 1.0/ t.Y2008) as V2008,sum (s.Y2009* 1.0/ t.Y2009) as V2009,sum (s.Y2010* 1.0/ t.Y2010) as V2010,
    sum (s.Y2011* 1.0 / t.Y2011) as V2011,sum (s.Y2012* 1.0/ t.Y2012) as V2012,sum (s.Y2013* 1.0/ t.Y2013) as V2013
    FROM sumasRevenue as s , sumasOperatingExpensive as t
    Where ID IS NULL and Name_Account IS NULL
    GROUP BY Name_Account, ID
    WITH ROLLUP
    select *
    from Aer_Lingus_Income_Statement_Historic
    Thank you in advance

  • SUM two fileds from different rows from the same table

    I would like to SUM two fileds from different rows from the same table but I don't know how to do that.
    E.g.
    BillingTransactionsIndex      CreateDate      UserType      UserIndex      TransType      Reference      Total      Balance
    2      6/5/2008 15:02      1      51      1      150      -288.2      -288.2
    5      6/8/2008 11:55      1      51      1      157      -1.58674      -289.787
    In the table above I want SUM fields Total and Balance for the first row and the the next row SUM 2nd row Total with 1st row Balance
    Please help
    Thanks

    SQL> with tbl as
      2  (select 1 as ID,  90 as total from dual
      3          union all
      4  select 2 as ID,  23 as total  from dual
      5          union all
      6  select 3 as ID,  15 as total  from dual
      7          union all
      8  select 4 as ID,  20 as total  from dual)
      9  select id , total, sum(total) over (order by ID) as balance from tbl
    10  /
            ID      TOTAL    BALANCE
             1         90         90
             2         23        113
             3         15        128
             4         20        148
    SQL>

  • Comparing totals from the same table

    I am trying to compare data from the same table..
    i am using an alias of the table to set up the select but i am running into a cartesian set.
    I am comparing data (totals) from different dates from the same table ; i have included the query which is giving me a problem:
    select a.date_in,b.date_in,a.Table_name,
    DECODE(a.schema_name,
    'EZLIVE','ITP','EZAC','ACT','OTHER')AS DEPT,
    a.type,
    a.status,
    a.TOTAL,
    b.total
    from agg_results a,agg_results b
    where a.schema_name=b.schema_name
    and to_char(a.date_in,'mm/dd/yyyy')='&date_in'
    and to_char(b.date_in,'mm/dd/yyyy')='&date_in';
    any help thanks
    Ellery

    I think you need to join in-line views instead of the tables directly. something like:
    SELECT a.date_in,b.date_in,a.table_name,a.dept,a.type,a.status,a.total,b.total
    FROM (SELECT date_in,table_name,
                 DECODE(schema_name,'EZLIVE','ITP',
                                    'EZAC','ACT','OTHER') dept,
                 type,status,total
          FROM agg_results
          WHERE date_in = to_date('&date_in','mm/dd/yyyy') a,
         (SELECT date_in,table_name,
                 DECODE(schema_name,'EZLIVE','ITP',
                                    'EZAC','ACT','OTHER') dept,
                 type,status,total
          FROM agg_results
          WHERE date_in = to_date('&date_in','mm/dd/yyyy') b
    WHERE a.dept = b.deptTTFN
    John

  • Two triggers in the same table and event

    If I created two triggers on the same table and event (before insert), which of them will be triggered first ?...
    The problem from the beginning is that I created the second one as after insert and in the body of the trigger I wrote (:new.xxx:= value) ... then an error (that it should be before insert trigger or update trigger), so I created it as before update ,,, but I have already before update trigger (for primary key)..... and the problem -I think- which of them start first...
    Can make the second one as after insert and make update statement instead of assigning (:new.xxx:= value).....
    Regards

    If I created two triggers on the same table and event
    (before insert), which of them will be triggered
    first ?...As already mentioned, prior to 11g the order of firing is undetermined.
    The problem from the beginning is that I created the
    second one as after insert and in the body of the
    trigger I wrote (:new.xxx:= value) ... then an error
    (that it should be before insert trigger or update
    trigger), so I created it as before update ,,, but I
    have already before update trigger (for primary
    key)..... and the problem -I think- which of them
    start first...If there is a conflict of interest inside the code then you will have to alter your design principle around this to cater for it. Also consider combining the code into a single before insert trigger to prevent any confusion.
    Can make the second one as after insert and make
    update statement instead of assigning (:new.xxx:=
    value).....Attempting to update or query the same table as is causing the trigger to fire will result in a mutating table error. You can't do this.

  • Retrieve data from the same table

    i have a table with following fields
    emp_no,name,salary,department,dept_prev,prev_emp_no.
    now i want retrieve emp_no,name,salary,department, from the data base for a perticular employeee number along with dept_prev
    but dept_prev is the prev_emp_no dept_prev
    now iam doing two query like this
    first query to retreive name,salary,department
    select name,salary,department from employee where emp_no = 10
    second to retrieve the dept_prev from the same table but this
    dept_prev must be based on prev_emp_no
    select dept_prev from employee where emp_no in(select prev_emp_no from employee where emp_no =10)
    can any one suggest to combine these two queries in a single sql statements, because all the fieldds are from the same table.
    Thanks

    Would this one solve it?
    SELECT emp.NAME, emp.salary, emp.department,
           prev_emp.dept_prev
      FROM employee emp,
           employee prev_emp
    WHERE emp.emp_no      = 10
       AND prev_emp.emp_no = emp.prev_emp_no;
    not tested
    C.

  • How to read the hierarchy data from the same table using loop in AMDP method

    Hi All,
    We have a requirement to get the top partner from BUT050 table.
    Here the Top parent is nothing but the top most in the hierarchy of the partners from BUT050.
    Example:
    For partner 1234 (BUT050-PARTNER1) there is partner 3523(BUT050-PARTNER2) one level above
    For partner 3523(BUT050-PARTNER1)  there is partner 4544 (BUT050-PARTNER2) last level .
    so in this case for the partner 1234 the Top parent is 4544 .
    I have created AMDP Procedure method to get the top-parnet and below given is the logic implemented in AMDP method.
    Here i have implemented a recursive logic with the WHILE loop to get the top most hierarchy partner from the same table BUT050
    IV_Parent is the input partner and ev_top_parent is the output value.
    AMDP Procedure Method:
        DECLARE lv_date VARCHAR(8) := TO_VARCHAR (current_date, 'YYYYMMDD');
        DECLARE found INT := 1;
              iv_partner1 =  SELECT partner1 FROM but050
                              WHERE partner2 = iv_partner
                              AND reltyp = :iv_hierarchy
                              AND date_to >=  :lv_date
                              AND date_from <= :lv_date;
         WHILE found <> 0  do
           select partner1 into ev_top_parent from :iv_partner1;
                           iv_partner1 =  SELECT partner1 FROM but050
                           WHERE partner2 in ( select partner1 from :iv_partner1 where partner1 is not null)
                           AND reltyp = 'ZBP004'
                           AND date_to >= :lv_date
                           AND date_from <= :lv_date;
           select COUNT ( partner1 ) INTO found FROM :IV_PARTNER1;
        END WHILE;
    This method is working fine, but here it is only taking one single partner and getting the top parent as output.
    Now i would like to convert this mehtod so as to accept n number of partners (not one single partner) as input and should process each partner to get the top parent.
    Could anyone guide me how can i handle the given AMDP method further so as to work some how it is within another loop from other AMDP method.
    Thanks.
    Regards,
    Laxman.P

    Hi
    Go to SE11 and enter the hierarchy table name.
    /BIC/H....(infoobject name)...and execute the table and select table entry and delete all....
    Thanks
    TG

  • How to update a table (CUSTOMER) on a Report Server with the data from the same table (CUSTOMER) from another server Transaction server?

    I had an interview question that is:
    How to update a table (Customer) on a server ex: Report Server with the data from the same table (Customer) From another server ex: Transaction server?
    Set up steps so inset, update or delete operation takes place across the servers.
    It would be great if someone please enlighten me in details about this process in MS SQL Server 2008 R2.
    Also please describe would it be different for SQL Server 2012?
    If so, then what are the steps?

    I had an interview question that is:
    How to update a table (Customer) on a server ex: Report Server with the data from the same table (Customer) from another server ex: Transaction server?
    Set up steps so that inset, update or delete operation gets done correctly across servers.
    I was not sure about the answer, it would be great if someone please put some light on this and explain in details about this process in MS SQL Server 2008 R2.
    Also it would be very helpful if you please describe would it be different for SQL Server 2012? If so, then what are the steps?

  • HT3455 I got two receipts from the same tv show I bought. How's that even possible? I clicked the 'buy season ' button the first time and there was an error so I clicked it again, and now, I apparently paid for it twice!  Apple is such a rip-off!

    I got two receipts from the same tv show I bought. How's that even possible? I clicked the 'buy season ' button the first time and there was an error so I clicked it again, and now, I apparently paid for it twice!  Apple is such a rip-off!

    Wow.
    Over react much?
    Check your purchase history.  See if it actually charged you twice.
    If it did then contact itunes support for a refund.
    No need be so over dramatic.

  • How to compare two entries in the same internal table

    Hi
    I hav e an internal table. I want to compare the entries in the internal table and delete the entries which is duplicates from the internal table. for ex. if plant 1000 is repeated two times. Then both the record of plant 1000 should be removed .
    Please suggest some idea.
    Thanks
    Subha

    Hi,
    Apply this code.
    include one more field in itab & jtab as delete_flag(1) type c.
    move itab to jtab.
    Loop at itab into wa_itab.
    lv_tabix = sy-tabix.
    Loop at jtab into wa_jtab where plant = wa_itab-plant.
    if sy-tabix ne lv_tabix.
    wa_itab-delete_flag = 'X'.
    endif.
    Endloop.
    modify itab from wa_itab transporting delete_flag.
    clear: wa_itab,wa_jtab.
    endloop.
    delete itab where delete_flag = 'X'.
    Now you have filtered ITAB with your desired results.
    It will surely help.
    Edited by: Adarsh Jain on Aug 18, 2010 7:57 AM
    Edited by: Adarsh Jain on Aug 18, 2010 7:58 AM

Maybe you are looking for