Return the Minimum from two tables in a Union

Hello
I have written a simple union query from our dialler service which has 2 tables, in inbound and an outbound table. A lead can show in any table depending how they came through to an agent and they can also show in both tables.  I need to return the
the first instance in the calltime column from both tables but also return all the other information.  I'm expecting multiple entries for the minimum calltime which is fine, I will be using a lookup in excel to extract the time.  Just to make matters
a little more difficult i'm having to use the OPENQUERY function because its within MYSQL.
SELECT O.Lead, O.DataList, O.[CallTime] AS 'CallDate', O.[Status], O.Uniqueid, O.Campaign, O.number, O.Advisor, 'Outbound' AS CallType
FROM OPENQUERY (dialler, 'SELECT * FROM dialler_outbound_data') O
WHERE O.CallTime >= '2014-12-01'
UNION
SELECT I.Lead, I.DataList, [CallTime] AS 'CallDate', I.[Status], I.Uniqueid, I.Campaign, I.Number, I.Advisor, 'Inbound' AS CallType
FROM OPENQUERY (dialler, 'SELECT * FROM dialler_inbound_data') I
WHERE I.CallTime >= '2014-12-01'
Can anyone help please?
Many Thanks
Rich

Hi Rich,
The use of the ROW_NUMBER function as mentioned and temp tables should do the trick.  See the code below...hope this helps.
SELECT ROW_NUMBER() OVER(ORDER BY O.[CallTime]) as 'Occurrance'
,O.Lead
,O.DataList
,O.[CallTime] AS 'CallDate'
,O.[Status]
,O.Uniqueid
,O.Campaign
,O.number
,O.Advisor
,'Outbound' AS CallType
INTO #TEMP1
FROM OPENQUERY (dialler, 'SELECT * FROM dialler_outbound_data') O
WHERE O.CallTime >= '2014-12-01'
SELECT ROW_NUMBER() OVER(ORDER BY I.[CallTime]) as 'Occurrance'
,I.Lead
,I.DataList
,[CallTime] AS 'CallDate'
,I.[Status]
,I.Uniqueid
,I.Campaign
,I.Number
,I.Advisor
,'Inbound' AS CallType
INTO #TEMP2
FROM OPENQUERY (dialler, 'SELECT * FROM dialler_inbound_data') I
WHERE I.CallTime >= '2014-12-01'
INSERT INTO #FINAL
SELECT * FROM #TEMP1
UNION
SELECT * FROM #TEMP2
SELECT * FROM #FINAL AS F WHERE F.Occurrance = 1
I'm new to this so if this helps, I could use your vote. 
Thanks,
 Zach

Similar Messages

  • 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

  • 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 to return mismatched rows from two tables?

    I have created two tables in the same database as below which gives the row
    count of tables across all databases before and after an DB restore
    operation.
    create table before_restore(db_name varchar(100),table_name
    varchar(1000),row_count int) insert into before_restore exec sp_msforeachdb 'USE
    [?]; select ''?'' as database_name,o.name,max(i.rowcnt ) From [?].sys.objects o
    inner join [?].sys.sysindexes i on o.object_id=i.id where o.type=''U'' group by
    o.name'
    create table after_restore(db_name varchar(100),table_name
    varchar(1000),row_count int) insert into after_restore exec sp_msforeachdb 'USE
    [?]; select ''?'' as database_name,o.name,max(i.rowcnt ) From [?].sys.objects o
    inner join [?].sys.sysindexes i on o.object_id=i.id where o.type=''U'' group by
    o.name'
    I want to compare these two tables and it should only return me rows that
    have changed after the restore operation is complete.
    Eg:
    Table xyz has rowcount of 100 before restore and the restore was not proper
    and after restore count is 50. So it should return me the result set as
    below;
    Db_name    Table_Name  row_count_before_restore    row_count_after_restore
    abc                   xyz                       100                              
       50
    Thanks!!!

    Something like below perhaps? Btw, I recommend using catalog view and dynamic management views instead of the old system tables (now called compatibility views)...
    SELECT
    COALESCE(a.db_name, b.db_name) AS db_name
    ,COALESCE(a.table_name, b.table_name) AS table_name
    ,a.row_count AS row_count_before_restore
    ,b.row_count AS row_count_after_restore
    FROM before_restore AS b FULL OUTER JOIN after_restore AS a ON b.db_name = a.db_name AND b.table_name = a.table_name
    WHERE b.row_count <> a.row_count OR b.db_name IS NULL OR a.db_name IS NULL
    Tibor Karaszi, SQL Server MVP |
    web | blog

  • Joining the data from two Tables

    I create a table with six months date from Jan to Jun. Another table with July trough Sept.
    Now I want one table in which I am going to at the end of the year have all 2007 fiscal data.
    I do not want to restore them ever back to the components. How do I do this?

    If I understand you correctly, I think you merely want to enlarge the first table enough to accommodate the data from the second table. Then select the cells in the second table and copy and paste them into the newly created space in the first table. Ask if you need more detail instructions on how to do this.

  • Question about retrieving data from two tables

    Hi everyone.
    I've been working on this and was wondering what the correct way of handling this would be.
    I have two tables, a Billing Table that contains invoices and related information, and a Payments Table that contains payments and related information to that.
    Both tables contain a Date Column for the date that the Invoice was generated or the Payment was made.
    I want to get a list of all Invoices and the respective payments if the invoice was generated between two dates OR the payment was made between these two dates.
    I can get a list of the invoices and their payments if the invoice was generated between those dates.  I can get a list of the payments if they were made between those dates.  But I can't seem to figure out how to do both.
    How do I Join two tables and have it return the data from both tables if either meets the required Date Period?
    Here is the SQL that I have so far.  This SQL returns all of the Invoices and Payments IF the Invoice was generated between these two dates (Or updated). 
    SELECT Billing.ID AS [BID], Billing.AttachmentName, Billing.BillingType, Billing.Invoice, Billing.Description, Billing.Amount, Billing.DateCreated AS [BillingDate],
    Payments.ID AS [PID], Payments.Type AS PaymentType, Payments.Payment, Payments.PaymentNote, Payments.Reason AS [BillReason], Payments.DateCreated AS [PaymentDate],
    Customers.ID AS [CID], COALESCE(NULLIF(Customers.Company,'') + ' - ','') + Customers.LName + ', ' + Customers.FName AS [Name],
    Jobs.ID AS [JID], Jobs.JobType, Jobs.JobStatus, Jobs.JobStatusDate
    FROM Billing LEFT OUTER JOIN Payments ON Payments.BillingID = Billing.ID
    RIGHT OUTER JOIN Customers ON Customers.ID = Billing.CustomerID
    RIGHT OUTER JOIN Jobs ON Jobs.ID = Billing.JobID
    WHERE
    Billing.BillingType = 'Invoice' AND Billing.PaidInFull = 'No' AND Billing.Collections = 'No' AND Billing.ChargeOff = 'No' AND Billing.Lien = 'No' AND Billing.InvoiceCanceled = 'No'
    AND (Billing.DateCreated >= '1/1/2014' AND Billing.DateCreated <= '8/13/14') OR (Billing.DateUpdated >= '1/1/14' AND Billing.DateUpdated <= '8/13/14')
    ORDER BY Name Asc, Billing.Invoice, PID
    Thanks for your help, I really appreciate it.
    -Matt-

    I don't quite follow your query, but your description leads me to think that you need the set of Billing IDs for bills that were created as defined or that have payments that were created as defined.  From that set of IDs you then simply want all Bills
    and their associated payments.  So how do you get that set of IDS?  One way is the union operator: 
    with allbill (billID) as (
    select ID from dbo.Billings where DateCreated between ...
    union 
    select BillingID from dbo.Payments where DateCreated between ... )
    select ...
    from allbill inner join dbo.Billings as bill on allbill.billID = bill.ID inner join dbo.Payments as pay 
    on bill.ID = pay.BillingID 
    order by ... ;
    Your description leads me to believe that you query is much more complicated, but the basic idea is the union in the CTE - generate one combined set of bill IDs that identify all your bills of interest.  Note that I assumed that a payment cannot exist
    with an associated billing.  

  • ALV OOps report- getting data from two tables and adding issue

    Hi,
    This is sales employee performance report.
    I need to select all the fields from two tables based on user input ie VKorg, sales employee .
    There is one field callled " Net sales"in both the tables.
    Based on sales employee number, i need to add that net sales which i get from two tables.
    I need to generate single report.
    Can you give some inputs reg. the select query.
    My idea is select all the data from both tables using join statement.
    Thanks

    Hi,
    I have written like this:
    select * from S002 as a join S006 as b
        into table ME->SS002_RAW[]
        where vkorg in me->select_parameters->SO_VKORG[] = vkorg in me->select_parameters->SO_VKORG[]
              and ZZSLSEMP01 in me->select_parameters->SO_so_empl[] = ZZSLSEMP02 in me->select_parameters->SO_so_empl[].
    when i do like that,
    I am getting error
    Incorrect structure of FROM clause . . . .     
    If you give some idea on this
    Edited by: Raja on Apr 22, 2009 11:19 AM

  • Can we create a BAM data Object from two tables

    Hi ,
    I want to pull the data from two tables and create a BAM data object, Is it possible in BAM?
    Do the needful
    Regards,
    Francis

    The sample way is using AQ on database. You can create a database view to join the tables. And create AQ on the view, create a ems to listen on the queue.

  • From two given tables, how do you fetch the values from two columns using values from one column(get values from col.A if col.A is not null and get values from col.B if col.A is null)?

    From two given tables, how do you fetch the values from two columns using values from one column(get values from col.A if col.A is not null and get values from col.B if col.A is null)?

    Hi,
    Use NVL or COALESCE:
    NVL (col_a, col_b)
    Returns col_a if col_a is not NULL; otherwise, it returns col_b.
    Col_a and col_b must have similar (if not identical) datatypes; for example, if col_a is a DATE, then col_b can be another DATE or it can be a TIMESTAMP, but it can't be a VARCHAR2.
    For more about NVL and COALESCE, see the SQL Language manual: http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions119.htm#sthref1310
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • Data from two tables in the same row in XML transformation

    Hi,
        I am using XML transformation for generating excel file which is to besent as email attachment.
        Here  I want to display the data from two internal tables in the same row in the excel. .I am using   <tt:loop ref=".<table name>"> ...  </tt:loop> for looping through the table. Can I loop two table simultaneously ? In that case how will I specify the fields in each table . Some of the fields in two tables are of same name and type.
    Please help...
    Thanks,
    Jissa

    Hello Brian,
    Thank you for your answer. It is approach I will use, I think. However let me ask: Would it be possible to have a Version in this layout, too? I mean to see, which value comes from Version A and which comes from Version B? Something like this:
    Calendar Month Version Sales Amount
    2011.01  B  200
    2011.02  B  300
    2011.03  A  260
    2011.04  A  230
    2011.05  A  200
    A

  • How to restrict the user(Schema) from deleting the data from a table

    Hi All,
    I have scenario here.
    I want to know how to restrict a user(Schema) from deleting the values from a table created in the same schema.
    Below is the example.
    I have created a table employee in abc schema which has two values.
    EMPLOYEE
    ABC
    XYZ
    In the above scenario the abc user can only fire select query on the EMPLOYEE table.
    SELECT * FROM EMPLOYEE;
    He should not be able to use any other DML commands on that table.
    If he uses then Insufficient privileges error should be thrown.
    Can anyone please help me out on this.

    Hi,
    kumar0828 wrote:
    Hi Frank,
    Thanks for the reply.
    Can you please elaborate on how to add policies for a table for just firing a select DML statement on table.See the SQL Packages and Types manual first. It has examples. You can also search the web for examples. This is sometimes called "Virtual Private Database" or VPD.
    If you have problems, post a specific question here. Include CREATE TABLE and INSERT statements to create a table as it exists before the policies go into effect, the PL/SQL code to create the policies, and additonal DML statements that will be affected by the policies. Show what the table should contain after each of those DML statements.
    Always say which version of Oracle you're using. Confirm that you have Enterprise Edition.
    See the forum FAQ {message:id=9360002}
    The basic idea behind row-level security is that it generates a string that is automatically added to SELECT and/or DML statement WHERE clauses. For example, if user ABC is only allowed to query a table on Sunday, then you might write a function that returns the string
    USER  != 'ABC'
    OR      TO_CHAR (SYSDATE, 'DY', 'NLS_DATE_LANGUAGE=ENGLISH') = 'SUN'So whenever any user says
    SELECT  *
    FROM    table_x
    ;what actually runs is:
    SELECT  *
    FROM    table_x
    WHERE   USER  != 'ABC'
    OR      TO_CHAR (SYSDATE, 'DY', 'NLS_DATE_LANGUAGE=ENGLISH') = 'SUN'
    ;If you want to prevent any user from deleting rows, then the policy function can return just this string
    0 = 1Then, if somone says
    DELETE  employee
    ;what actually gets run is
    DELETE  employee
    WHERE   0 = 1
    ;No error will be raised, but no rows will be deleted.
    Once again, it would be simpler, more efficient, more robust and easier to maintain if you just created the table in a different schema, and not give DELETE privileges.
    Edited by: Frank Kulash on Nov 2, 2012 10:26 AM
    I just saw the previous response, which makes some additional good points (e.g., a user can always TRUNCATE his own tables). ALso, if user ABC applies a security policy to the table, then user ABC can also remove the policy, so if you really want to prevent user ABC from deleting rows, no matter how hard the user tries, then you need to create the policies in a different schema. If you're creating things in a different schema, then you might as well create the table in a different schema.

  • Select from two tables and insert into a third

    I'm trying to do a select from two tables and do an insert into a third table from the two resulting columns.
    I have the following....
    DECLARE
    tempsid number;
    temphostid number;
    BEGIN
    select "DBSID_ID","ID" into tempsid,temphostid from "DBSIDS","SERVERS"
    where "HOST_SID" like '%'||"DBSID_NAME"||'%'
    and "HOST_NAME" not like 'vio%'
    and exists (select "DBSID_NAME" from DBSIDS)
    order by "DBSID_NAME";
    insert into "DBSID_LOOKUP" ("SIDLOOKUP_ID", "SERVERLOOKUP_ID")
    values(tempsid, temphostsid);
    END;
    run;
    I get the error ....
    ORA-06550: line 11, column 18:
    PL/SQL: ORA-00984: column not allowed here
    ORA-06550: line 10, column 1:
    PL/SQL: SQL Statement ignored
    1. DECLARE
    2. tempsid number;
    3. temphostid number;

    okay ... I tried a different way ...
    DECLARE
    a number;
    b number;
    BEGIN
    select "DBSID_ID","ID" into a,b from "DBSIDS","SERVERS"
    where "HOST_SID" like '%'||"DBSID_NAME"||'%'
    and "HOST_NAME" not like 'vio%'
    and exists (select "DBSID_NAME" from DBSIDS)
    order by "DBSID_NAME";
    insert into "DBSID_LOOKUP" (SIDLOOKUP_ID, SERVERLOOKUP_ID) values (a, b);
    END;
    and now it whines about ...
    ORA-01422: exact fetch returns more than requested number of rows

  • 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.

  • Selecting columns from two table is slow but same

    I am selecting 27 columns from two tables
    which running for more than 30 minutes. but
    if I select count(*) with the same query
    except the columns it is coming in seconds.
    Where is the error?

    If you post
    1) The table definitions for the underlying tables
    2) The indexes that are on the tables
    3) The two SQL statements you're running
    4) The explain plan for both statements
    we can probably be of some assistance.
    My guess is that the count(*) is able to return much more quickly because the optimizer is able to use a significantly faster query plan that is based on an index which the longer-running query cannot utilize. Without the information I've requested, though, it's hard to do more than speculate.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • How to return course  data  from different tables from a procedure

    I have a procedure which must return information from two tables:
    The sturcture of tables is as below:
    Table 1:
    id,
    name,
    property,
    type
    Table 2:
    id1
    id2 ,
    property.
    id1 of table2 refers to id attribute of table1. ie id is the foreign key for table2.
    the tables are defined such that for corresponding to each id in table1 there would
    be two or more rows in table2.
    Now in the procedure given the id, i need to retrieve information from table1 and also all the rows in table2 which refers to id2.I want to return a cursor.How can i do this.
    eg:
    if table 1 has an entry with id 2
    and table 2 has three entries with id1 referring to id(i.e id1=2)..I need to return the table1 entry with id=2 and three entires from table2 with id1=2.
    If cursors are not appropriate, what other alternative methods can be used.
    Any suggestions would be of great help.

    thanks for the reply,
    The result set would be returned to the client .....which would do further processing.The client does not even know that the data is organized in two tables..Therefore given an id, client would expect to have all the information...i.e the info from table 1 and info from table 2 where the relation ship between id and other ids are stored.
    i.e say client has id=6.This id has property,name,etc stored in table1.
    This id can further be related to any number other of ids.It can be related 2,5,100,or may be even 10000s of other ids.This mapping between the original id and other ids..are stored in table2.
    So given the id by the client , i would want to return property of the ids itself along with all the ids that it is related to .
    I want to achieve this.....

Maybe you are looking for