How do you Select data from two tables with similar data amd merge the output together.

I have two Tables containing Sales Data. I want to read the Table a sort by date and accumulate dollars by order date. Then I want to read the second table and accumulate these dollar amounts by date and then merge the records together so that I gave 1 row
with amounts for type A and amounts for type b.
Here are the tables I am looking at.
Select Cast(J.Order_Date As Varchar(11))) As [Order Date]
          ,Sum(Case when Sales_Code like '%Comm%' then (J.Order_Quantity * J.Unit_Price) Else 0 end) As Decimal(11,2) As [Job Comm]
          ,Sum(Case when Sales_Code = '5-Day' then (J.Order_Quantity * J.Unit_Price) Else 0 end) As Decimal(11,2) As [Job Auto]
          ,Sum(Case when Sales_Code like '%Auto%" then (J.Order_Quantity * J.Unit_Price) Else 0 end) As Decimal(11,2) As [Job Auto]
          ,Sum(Case when Sales_Code = '' then (J.Order_Quantity * J.Unit_Price) Else 0 end) As Decimal(11,2) As [Job Fixed]
          ,Sum(Case when Sales_Code = 'XX' then (J.Order_Quantity * J.Unit_Price) Else 0 end) As Decimal(11,2) As [SO Comm)
          ,Sum(Case when Sales_Code = 'YY' then (J.Order_Quantity * J.Unit_Price) Else 0 end) As Decimal(11,2) As [SO Auto)
          ,Sum(Case when Sales_Code = 'ZZ' then (J.Order_Quantity * J.Unit_Price) Else 0 end) As Decimal(11,2) As [SO Fixed)
from [PRODUCTION].dbo.Job As J
union all
Select Cast(SH.Order_Date As Varchar(11))) As [Order Date]
          ,Sum(Case when Sales_Code like '%Comm%' then SD.Ext_Amt Else 0 end) As Decimal(11,2) As [SO Comm]
          ,Sum(Case when Sales_Code = '5-Day'     then SD.Ext_Amt Else 0 end) As Decimal(11,2) As [SO Auto]
          ,Sum(Case when Sales_Code like '%Auto%" then SD.Ext_Amt Else 0 end) As Decimal(11,2) As [SO Auto]
          ,Sum(Case when Sales_Code = ''          then SD.Ext_Amt Else 0 end) As Decimal(11,2) As [SO Fixed]
          ,Sum(Case when Sales_Code = 'XX' then SD.Ext_Amt Else 0 end) As Decimal(11,2) As [Job Comm)
          ,Sum(Case when Sales_Code = 'YY' then SD.Ext_Amt Else 0 end) As Decimal(11,2) As [Job Auto)
          ,Sum(Case when Sales_Code = 'ZZ' then SD.Ext_Amt Else 0 end) As Decimal(11,2) As [Job Fixed)
from [PRODUCTION].dbo.SO_Detail As SD
Inner Join [PRODUCTION].dbo.SO_Header As SH
    on SD.Sales_Order = SH.Sales_Order
Group by J.Order_Date
Order by J.Order_Date Desc
Looking for output like
Order Date   Job Comm   Job AUto   Job Fixed    SO Comm  SO AUto  SO Fixed
Mar-11-2014    100.00     250.00       50.00     200.00   300.00    400.00
Mar-10-2014    500.00     340.00        0.00     110.00   400.00    500.00
Mar-09-2014    600.00     333.00       56.00     210.00   500.00    300.00
Thanks for your help
SWProduction

Seeing the output it looks like what you need is this
select COALESCE(p.[Order Date],q.[Order Date]) AS [Order Date],
COALESCE([Job Comm],0) AS [Job Comm],
COALESCE([Job AUto],0) AS [Job AUto],COALESCE([Job Fixed],0) AS [Job Fixed],COALESCE([SO Comm],0) AS [SO Comm],COALESCE([SO AUto],0) AS [SO AUto],COALESCE([SO Fixed],0) AS [SO Fixed]
from
Select Cast(J.Order_Date As Varchar(11))) As [Order Date]
,Sum(Case when Sales_Code like '%Comm%' then (J.Order_Quantity * J.Unit_Price) Else 0 end) As Decimal(11,2) As [Job Comm]
,Sum(Case when Sales_Code = '5-Day' then (J.Order_Quantity * J.Unit_Price) Else 0 end) As Decimal(11,2) As [Job Auto]
,Sum(Case when Sales_Code like '%Auto%" then (J.Order_Quantity * J.Unit_Price) Else 0 end) As Decimal(11,2) As [Job Auto]
,Sum(Case when Sales_Code = '' then (J.Order_Quantity * J.Unit_Price) Else 0 end) As Decimal(11,2) As [Job Fixed]
,Sum(Case when Sales_Code = 'XX' then (J.Order_Quantity * J.Unit_Price) Else 0 end) As Decimal(11,2) As [SO Comm)
,Sum(Case when Sales_Code = 'YY' then (J.Order_Quantity * J.Unit_Price) Else 0 end) As Decimal(11,2) As [SO Auto)
,Sum(Case when Sales_Code = 'ZZ' then (J.Order_Quantity * J.Unit_Price) Else 0 end) As Decimal(11,2) As [SO Fixed)
from [PRODUCTION].dbo.Job As J
)p
full join
Select Cast(SH.Order_Date As Varchar(11))) As [Order Date]
,Sum(Case when Sales_Code like '%Comm%' then SD.Ext_Amt Else 0 end) As Decimal(11,2) As [SO Comm]
,Sum(Case when Sales_Code = '5-Day' then SD.Ext_Amt Else 0 end) As Decimal(11,2) As [SO Auto]
,Sum(Case when Sales_Code like '%Auto%" then SD.Ext_Amt Else 0 end) As Decimal(11,2) As [SO Auto]
,Sum(Case when Sales_Code = '' then SD.Ext_Amt Else 0 end) As Decimal(11,2) As [SO Fixed]
,Sum(Case when Sales_Code = 'XX' then SD.Ext_Amt Else 0 end) As Decimal(11,2) As [Job Comm)
,Sum(Case when Sales_Code = 'YY' then SD.Ext_Amt Else 0 end) As Decimal(11,2) As [Job Auto)
,Sum(Case when Sales_Code = 'ZZ' then SD.Ext_Amt Else 0 end) As Decimal(11,2) As [Job Fixed)
from [PRODUCTION].dbo.SO_Detail As SD
Inner Join [PRODUCTION].dbo.SO_Header As SH
on SD.Sales_Order = SH.Sales_Order
Group by J.Order_Date
)q
on p.[Order Date] = q.[Order Date]
Order by COALESCE(p.[Order Date],q.[Order Date]) Desc
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Similar Messages

  • How to compare two rows from two table with different data

    how to compare two rows from two table with different data
    e.g.
    Table 1
    ID   DESC
    1     aaa
    2     bbb
    3     ccc
    Table 2
    ID   DESC
    1     aaa
    2     xxx
    3     ccc
    Result
    2

    Create
    table tab1(ID
    int ,DE char(10))
    Create
    table tab2(ID
    int ,DE char(10))
    Insert
    into tab1 Values
    (1,'aaa')
    Insert
    into tab1  Values
    (2,'bbb')
    Insert
    into tab1 Values(3,'ccc')
    Insert
    into tab1 Values(4,'dfe')
    Insert
    into tab2 Values
    (1,'aaa')
    Insert
    into tab2  Values
    (2,'xx')
    Insert
    into tab2 Values(3,'ccc')
    Insert
    into tab2 Values(6,'wdr')
    SELECT 
    tab1.ID,tab2.ID
    As T2 from tab1
    FULL
    join tab2 on tab1.ID
    = tab2.ID  
    WHERE
    BINARY_CHECKSUM(tab1.ID,tab1.DE)
    <> BINARY_CHECKSUM(tab2.ID,tab2.DE)
    OR tab1.ID
    IS NULL
    OR 
    tab2.ID IS
    NULL
    ID column considered as a primary Key
    Apart from different record,Above query populate missing record in both tables.
    Result Set
    ID ID 
    2  2
    4 NULL
    NULL 6
    ganeshk

  • Cartesian of data from two tables with no matching columns

    Hello,
    I was wondering – what’s the best way to create a Cartesian of data from two tables with no matching columns in such a way, so that there will be only a single SQL query generated?
    I am thinking about something like:
    for $COUNTRY in ns0: COUNTRY ()
    for $PROD in ns1:PROD()
    return <Results>
         <COUNTRY> {fn:data($COUNTRY/COUNTRY_NAME)} </COUNTRY>
         <PROD> {fn:data($PROD/PROD_NAME)} </PROD>
    </Results>
    And the expected result is combination of all COUNTRY_NAMEs with all PROD_NAMEs.
    What I’ve noticed when checking query plan is that DSP will execute two queries to have the results – one for COUNTRY_NAME and another one for PROD_NAME. Which in general results in not the best performance ;-)
    What I’ve noticed also is that when I add something like:
    where COUNTRY_NAME != PROD_NAME
    everything is ok and there is only one query created (it's red in the Query plan, but still it's ok from my pov). Still it looks to me more like a workaround, not a real best approach. I may be wrong though...
    So the question is – what’s the suggested approach for such queries?
    Thanks,
    Leszek
    Edited by xnts at 11/19/2007 10:54 AM

    Which in general results in not the best performanceI disagree. Only for two tables with very few rows, would a single sql statement give better performance.
    Suppose there are 10,000 rows in each table - the cross-product will result in 100 million rows. Sounds like a bad idea. For this reason, DSP will not push a cross-product to a database. It will get the rows from each table in separate sql statements (retrieving only 20,000 rows) and then produce the cross-product itself.
    If you want to execute sql with cross-products, you can create a sql-statement based dataservice. I recommend against doing so.

  • Data from two tables with no key fields

    Hi Friends,
    I want to retrieve data from mara and mseg tables,matnr from mara and menge from mseg but problem is there is no key fields
    from these two tables how can i retrieve the data from these two tables?
    regards,
    bikash

    Hi,
    You need to have a common field between 2 tables if you want to put a join between them.
    Or otherwise,
    Find the check table of the primary keys of the tables.
    Try to find the common fields from one of the check tables of the primary keys.
    Example,
    If you want to join tables A and B.
    Both tables don't contain common fields.
    A has primary key fields X and Y.
    go to check table of X or Y.
    Let check table of X is C.
    check any field in C which are exist in table B.
    Join tables A and C.
    Based on this pick the data from B.
    Regards,
    Prashant

  • How to use common object from two tables with out join.

    HI,
    I have two tables called A & B In A table i have the following objects
    1.weekend
    2.S1(measure)
    3.S2(measure)
    4.S3(measure)
    5.S4(measure)
    And In B table i have followning columns
    1.week end
    2.p1(measure)
    3.p2(measure)
    4.p3(measure)
    5.p4(measure)
    Now in universe i created all the measure objects i.e.s1,s2,s3,s4,p1,p2,p3,p4 A.weekend,B.weekend.
    instead of using week end two times i wnt to use only once because this is common in both table.
    if i use join between these tables i am getting values fine
    But With out join is there any thing to do in universe level to create common objects to use from both the tables..I tried using aggregate awareness but while reporting it is taking as two SQL.which is not synchronized.
    Please help me on this ...

    hi,
    Although  Weekend column is present in both tables, by creating a single Object in Universe, Universe can identify relationship with only table referenced in Object Creation.
    So, there will be no identification of relationship with other table measures.
    Obviously, you need to create 2 Weekend objects in Universe (in two classes).
    Case 1: You need not join these two tables in Universe. When you create 2 Queries in WEBI, automatcially Weekend objects are synchronized (if both are of same datatype)
    Case 2: If you join these two tables in Universe, Obviously,
    your SQL may contain Weekend from Table1, measures from Table 2
    or
    your SQL may contain Weekend from Table2, measures from Table 1
    Finally, You need to create 2 objects in Universe. But your query may contain a single Object based on Case 2.
    Regards,
    Vamsee

  • Select data from two tables...!

    HI Experts...!
    i m a beginner user and i want to select data from two tables proj and prps.....using joins.....and internal tables i have written a code...
    SELECT prps~pspnr
           prps~objnr
           prps~psphi
           proj~ernam
           proj~erdat
           proj~pspnr
    INTO  table itab   -
    itab is internal table
    FROM prps inner join proj
    WHERE pspnr in p_no and prpspsphi = projpspnr.
    but there is error in from clause ..please help me....
    Advance thanx....

    Hi,
    check the sample code bellow above two reply will solve out your problem but one more extra line in your code pointed out bellow.
    TABLES: prps, proj.
    TYPES:  BEGIN OF ty_test,
            pspnr LIKE prps-pspnr,
            objnr LIKE prps-objnr,
            psphi LIKE prps-psphi,
            ernam LIKE proj-ernam,
            erdat LIKE proj-erdat,
            END OF ty_test.
    DATA: itab TYPE STANDARD TABLE OF ty_test WITH HEADER LINE.
    SELECT-OPTIONS: p_no FOR prps-pspnr.
    SELECT  prps~pspnr
            prps~objnr
            prps~psphi
            proj~ernam
            proj~erdat
    *        proj~pspnr " No need for this you have selected this in
    *     the first line because it is commone so you only need to select from any one
            INTO TABLE itab
    FROM prps INNER JOIN proj ON ( prps~pspnr = proj~pspnr  )
    WHERE prps~pspnr IN p_no.
    Best Regards,
    Faisal
    Edited by: Rob Burbank on Dec 24, 2009 12:24 PM

  • Selecting data from two tables

    I am trying to select data from two tables.  The only problem that I am running into, is that i am only seeing results from my 'uploads' table.  there is also a record in documents where user = 1 that should show up.  here is my sql:
    $userIDNum = 1;
    $sql="Select *
    from uploads, documents
    WHERE uploads.user = documents.user AND uploads.user = $userIDNum
    ORDER BY uploads.title ASC, documents.title ASC";

    You'll need to explain a little more about your data and what you are trying to accomplish. Your current sql will select all columns from both the uploads and documents tables but only rows where the user id in both tables match, AND the user id equals 1. Is that not what you are seeing? Where's the code that outputs the results?

  • To Select the data from two table one is transp table and onther is cluster

    Hi All,
    I want to select the data from two tables
    Here i am giving with an example.
    Fileds: kunnr belnr from bseg.  table bseg
    fields: adrnr from kna1     table: kna1.
    Know i want to put these into one internal table based on kunnr and belnr.
    Thanks in advance.
    Ramesh

    Hi,
       U cant use joins on cluster table and BSEG is a cluster table so use FOR  ALL ENTRIES for taht
    refer this code
    *&      Form  sub_read_bsak
          text
    -->  p1        text
    <--  p2        text
    FORM sub_read_bsak.
    *--Select data from BSAK Table
      SELECT lifnr
             augdt
             augbl
             gjahr
             belnr
             xblnr
             blart
             dmbtr
             mwskz
             mwsts
             sgtxt
             FROM bsak
             INTO CORRESPONDING FIELDS OF TABLE it_bsak
             WHERE belnr IN s_belnr
             AND   augdt IN s_augdt.
      IF sy-subrc EQ 0.
    *--Sort table by accounting document and vendor number
        SORT it_bsak BY belnr lifnr.
      ENDIF.
    ENDFORM.                    " sub_read_bsak
    *&      Form  sub_read_bseg
          text
    -->  p1        text
    <--  p2        text
    FORM sub_read_bseg.
      IF NOT it_bsak[] IS INITIAL.
    *--Select data from BSEG table
        SELECT belnr
               gjahr
               shkzg
               kostl
               hkont
               ebeln
               ebelp
               FROM bseg
               INTO CORRESPONDING FIELDS OF TABLE it_bseg
               FOR ALL ENTRIES IN it_bsak
               WHERE belnr EQ it_bsak-belnr
               AND   gjahr EQ it_bsak-gjahr
               AND   shkzg EQ 'S'.
        IF sy-subrc EQ 0.
    *--Sort table by accounting document
          SORT it_bseg BY belnr.
        ENDIF.
      ENDIF.
    ENDFORM.                    " sub_read_bseg

  • How to select data from a table using a date field in the where condition?

    How to select data from a table using a date field in the where condition?
    For eg:
    data itab like equk occurs 0 with header line.
    select * from equk into table itab where werks = 'C001'
                                                      and bdatu = '31129999'.
    thanks.

    Hi Ramesh,
    Specify the date format as YYYYMMDD in where condition.
    Dates are internally stored in SAP as YYYYMMDD only.
    Change your date format in WHERE condition as follows.
    data itab like equk occurs 0 with header line.
    select * from equk into table itab where werks = 'C001'
    and bdatu = <b>'99991231'.</b>
    I doubt check your data base table EQUK on this date for the existince of data.
    Otherwise, just change the conidition on BDATU like below to see all entries prior to this date.
    data itab like equk occurs 0 with header line.
    select * from equk into table itab where werks = 'C001'
    and <b> bdatu <= '99991231'.</b>
    Thanks,
    Vinay
    Thanks,
    Vinay

  • Retrive data from two tables into one internal table.

    Hi SDN,
    I am downloading the Assets data from two tables ANLA,ANLZ.
    there is a common field ANL1in both tables and i have to retrive the data by using anl1 into the internal table.
    can you please send me the SELECT Syntax for this probl.....
    Thank you & Regards,
    Manoj

    Hi manoj,
    Please see the following sample code. But kindly don't use join as it may hamper ur performance. No trouble in using two select query.
    data: begin of itab occurs 0,
            BUKRS like anla-BUKRS,
            ANLN1 like anla-ANLN1,
           BDATU like anlz-BDATU,
            end of itab.
    select anlabukrs anlaANLN1 anlzBDATU  into corresponding fields of table itab from anla inner join anlz on anlaanl1 eq anlz~anl1 where (logexp).
    Please come back for any clarification.
    Thanks and Regards,
    saurabh

  • Select max date from a table with multiple records

    I need help writing an SQL to select max date from a table with multiple records.
    Here's the scenario. There are multiple SA_IDs repeated with various EFFDT (dates). I want to retrieve the most recent effective date so that the SA_ID is unique. Looks simple, but I can't figure this out. Please help.
    SA_ID CHAR_TYPE_CD EFFDT CHAR_VAL
    0000651005 BASE 15-AUG-07 YES
    0000651005 BASE 13-NOV-09 NO
    0010973671 BASE 20-MAR-08 YES
    0010973671 BASE 18-JUN-10 NO

    Hi,
    Welcome to the forum!
    Whenever you have a question, post a little sample data in a form that people can use to re-create the problem and test their ideas.
    For example:
    CREATE TABLE     table_x
    (     sa_id          NUMBER (10)
    ,     char_type     VARCHAR2 (10)
    ,     effdt          DATE
    ,     char_val     VARCHAR2 (10)
    INSERT INTO table_x (sa_id,  char_type, effdt,                          char_val)
         VALUES     (0000651005, 'BASE',    TO_DATE ('15-AUG-2007', 'DD-MON-YYYY'), 'YES');
    INSERT INTO table_x (sa_id,  char_type, effdt,                          char_val)
         VALUES     (0000651005, 'BASE',    TO_DATE ('13-NOV-2009', 'DD-MON-YYYY'), 'NO');
    INSERT INTO table_x (sa_id,  char_type, effdt,                          char_val)
         VALUES     (0010973671, 'BASE',    TO_DATE ('20-MAR-2008', 'DD-MON-YYYY'), 'YES');
    INSERT INTO table_x (sa_id,  char_type, effdt,                          char_val)
         VALUES     (0010973671, 'BASE',    TO_DATE ('18-JUN-2010', 'DD-MON-YYYY'), 'NO');
    COMMIT;Also, post the results that you want from that data. I'm not certain, but I think you want these results:
    `    SA_ID LAST_EFFD
        651005 13-NOV-09
      10973671 18-JUN-10That is, the latest effdt for each distinct sa_id.
    Here's how to get those results:
    SELECT    sa_id
    ,         MAX (effdt)    AS last_effdt
    FROM      table_x
    GROUP BY  sa_id
    ;

  • Populate ADF Rich Table taking data from two tables of database

    Hi,
    Can anyone please guide me as to how I can populate ADF Rich Table taking data from two tables A and B of a database.
    The condition is
    I want to fetch row 1 from table A and populate into ADF Rich Table at row 1
    then
    I want to fetch row 1 from table B and populate into ADF Rich Table at row 2
    and so on....
    Many thanks for your help..
    Regards,
    Rohit

    The better place where you will learn:
    http://download.oracle.com/docs/cd/E12839_01/web.1111/b31974/bcquerying.htm

  • Creating a external content type for Read and Update data from two tables in sqlserver using sharepoint designer

    Hi
    how to create a external content type for  Read and Update data from two tables in  sqlserver using sharepoint designer 2010
    i created a bcs service using centraladministration site
    i have two tables in sqlserver
    1)Employee
    -empno
    -firstname
    -lastname
    2)EmpDepartment
    -empno
    -deptno
    -location
    i want to just create a list to display employee details from two tables
    empid firstname deptno location
    and same time update  in two tables
    adil

    When I try to create an external content type based on a view (AdventureWorks2012.vSalesPerson) - I can display the data in an external list.  When I attempt to edit it, I get an error:
    External List fails when attached to a SQL view        
    Sorry, something went wrong
    Failed to update a list item for this external list based on the Entity (External Content Type) 'SalesForce' in EntityNamespace 'http://xxxxxxxx'. Details: The query against the database caused an error.
    I can edit the view in SQL Manager, so it seems strange that it fails.
    Any advice would be greatly GREATLY appreciated. 
    Thanks,
    Randy

  • Fetch the data from two tables

    hell all
    i want to fetch the data from two tables, one is from internal table and another one is data base table. what syntax i have to use either FOR ALL ENTRIES or INNER JOIN?

    hi
    Use FOR ALL ENTRIES.
    see the sample code
      select * into table tvbrk from vbrk
                                where fkart in ('F2', 'F3', 'RE',
                                           'ZVEC' , 'ZVEM' , 'ZVED',
                                           'S1')
                                and erdat in so_erdat
                                and kunag in s_kunag. 
                                      erdat in so_erdat
                               and   fkart in ('F2', 'F3', 'RE',
                                                 'ZVEC' , 'ZVEM').
    if not tvbrk is initial.
        select * into table t_zregion from zregion
                      for all entries in tvbrk
                       where country = tvbrk-land1
                       and   region = s_regio.
      endif.
    thanks
    sitaram

  • How can I select columns from a table EMP, using Select statement?.

    Hi Friends,
    How can I select columns from a table EMP?.
    I want to select columns of EMP table, using select statement.
    Please reply me urgently.
    Shahzad

    Something like this:
    scott@DBA> select empno,ename,job from emp;
         EMPNO ENAME      JOB
          7369 SMITH      CLERK
          7499 ALLEN      SALESMAN
          7521 WARD       SALESMAN
          7566 JONES      MANAGER
          7654 MARTIN     SALESMAN
          7698 BLAKE      MANAGER
          7782 CLARK      MANAGER
          7788 SCOTT      ANALYST
          7839 KING       PRESIDENT
          7844 TURNER     SALESMAN
          7876 ADAMS      CLERK
          7900 JAMES      CLERK
          7902 FORD       ANALYST
          7934 MILLER     CLERK
    14 rows selected.Check the documentation:
    http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10002.htm#sthref9697
    Message was edited by:
    Delfino Nunez

Maybe you are looking for

  • Survey Export to Excel - Not all columns are exported

    I have Survey in SharePoint 2013 with questions expecting different answers - radio button options / Ratings / Multi line text, etc. Settings choosen - Read thier own responses, create and edit their own responses I have full control over the site wh

  • Windows 7 Crashes/Freezes when playing ANY Video files

    lets see can anyone get their head around this one as it is driving me round the bend.  So... I have a media centre PC connected to my HDTV by VGA cable. I ran the PC on XP for a long time but last December, I upgraded it to Windows 7 along with my l

  • Parallel port printer connection

    I have an HP 6122 parallel port printer which I've attached to my MacBook Pro running on OSX 10.4.11 through a connecting cable to the USB port (I've tried both the left and right USB port). I've downloaded driver from HP, but computer doesn't see th

  • Color for each item ring

    Hello, Is it possible to assign a different color for each item in a ring control ? See what I start in attached file. Thanks Attachments: enumeration_avec_couleur.vi ‏8 KB

  • Fios external 2TB drive filled up, now no access to it

    I've been running my fios with external 2TB for 2 years now.  After letting it get to 100% full ( in the DVR section of the menus where it shows space used ) by accident, I can now no longer see anything that is stored there.  I see that the set is r