How to combine records using SQL?

If I have the following data:
Table A
order_no company_code
O001 C001
Table B
order_no po_no
O001 P001
O001 P002
O001 P003
Now, I want to combine the data as:
View A
order_no company_code po_no
O001 C001 P001, P002, P003
If can it be realized using SQL?
Thanks and Best Regards,
Su Qian

Hi Su Qian,
To get the result like this you should write a function and call that in the select query.
The function could be like this:
CREATE OR REPLACE FUNCTION TEST(p_order_no IN B.order_no%TYPE ) RETURN VARCHAR2 IS
v_po_no VARCHAR2(100);
BEGIN
FOR c IN (SELECT po_no FROM B WHERE order_no = p_order_no)
LOOP
IF v_po_no IS NULL THEN
v_po_no := c.po_no;
ELSE
v_po_no := v_po_no||','||c.po_no;
END IF;
END LOOP;
RETURN v_po_no;
END;
Now you issue the query like this:
select order_no, company_code, test(order_no) po_no from a;
This will return you what you want.
Hope this will help you.
Best Regards,
Ramesh Rathi.
OCP - DBA.
Zensar Tech Ltd.
[email protected]
If I have the following data:
Table A
order_no company_code
O001 C001
Table B
order_no po_no
O001 P001
O001 P002
O001 P003
Now, I want to combine the data as:
View A
order_no company_code po_no
O001 C001 P001, P002, P003
If can it be realized using SQL?
Thanks and Best Regards,
Su Qian

Similar Messages

  • How to combine records using function

    Hi, all
    I have an oracle 10g running on a RH linux e3 server.
    I have two tables like this:
    CREATE TABLE "IMMUNODATA"."DEMOGRAPHICS" (
    "SUBJECTID" INTEGER NOT NULL,
    "WORKID" INTEGER,
    "OMRFHISTORYNUMBER" INTEGER,
    "OTHERID" INTEGER,
    "BARCODE" INTEGER,
    "GENDER" VARCHAR2(1),
    "DOB" DATE,
    "RACEAI" INTEGER,
    "RACECAUCASIAN" INTEGER,
    "RACEAA" INTEGER,
    "RACEASIAN" INTEGER,
    "RACEPAC" INTEGER,
    "RACEHIS" INTEGER,
    "RACEOTHER" VARCHAR2(50),
    "SSN" VARCHAR2(11),
    PRIMARY KEY("SUBJECTID") VALIDATE
    CREATE TABLE "IMMUNODATA"."BIOPSY" (
    "ID" INTEGER NOT NULL,
    "THEDATE" DATE ,
    "SUBJECTID" INTEGER NOT NULL,
    "TISSUE" VARCHAR2(50),
    "DATEOFBIOPSY" DATE ,
    "FACILITYWHEREDONE" VARCHAR2(200),
    "RESULT" VARCHAR2(500),
    "BARCODE" INTEGER,
    PRIMARY KEY("ID") VALIDATE,
    FOREIGN KEY("SUBJECTID") REFERENCES "IMMUNODATA"."DEMOGRAPHICS" ("SUBJECTID") VALIDATE
    the result of one selection is like this:
    select subjectid, barcode, tissue, dateofbiopsy from demographics left join biopsy;
    subjectid barcode tissue, dateofbiopsy
    1 500001 lung 2003/1/1
    1 500001 kidney 2005/3/4
    I want to have a view of this
    subjectid barcode biopsy dateofbiopsy
    1 500001 lung,kidney 2003/1/1,2005/3/4
    I created a function like this:
    CREATE OR REPLACE FUNCTION TEST(p_subjectid IN immunodata.biopsy.subjectid%TYPE ) RETURN VARCHAR2 IS
    v_tissue VARCHAR2(100),v_dateofbiopsy DATE;
    BEGIN
    FOR c IN (SELECT tissue, dateofbiopsy FROM immunodata.biopsy WHERE subjectid = p_subjectid)
    LOOP
    IF v_tissue IS NULL and v_dateofbiopsy IS NULL THEN
    v_tissue := c.tissue;
    v_dateofbiopsy :=c.dateofbiopsy;
    ELSE
    v_tissue := v_tissue||','||c.tissue;
    v_dateofbiopsy :=v_dateodbiopsy||','||c.dateofbiopsy;
    END IF;
    END LOOP;
    RETURN v_tissue,v_dateofbiopsy;
    END;
    The error says:
    Warning: Function created with compilation errors.
    SQL> show errors
    Errors for FUNCTION TEST:
    LINE/COL ERROR
    2/23 PLS-00103: Encountered the symbol "," when expecting one of the
    following:
    := ; not null default character
    The symbol "; was inserted before "," to continue.
    14/16 PLS-00103: Encountered the symbol "," when expecting one of the
    following:
    . ( * @ % & = - + ; < / > at in is mod remainder not rem
    <an exponent (**)> <> or != or ~= >= <= <> and or like
    between || multiset member SUBMULTISET_
    The symbol ". was inserted before "," to continue.
    So could I combine multiple fields in one function?
    Thanks!
    Qian

    Also, in addition to Warren's response, the "RETURN" keyword should be followed by a single VARCHAR2 value (or a NULL):
    test@ORA10G>
    test@ORA10G> create or replace function my_function (s varchar2) return varchar2 is
      2    v_str1 varchar2(100);
      3    v_str2 varchar2(100);
      4  begin
      5    v_str1 := '*'||s||'*';
      6    v_str2 := '~'||s||'~';
      7    return v_str1,v_str2;
      8  end;
      9  /
    Warning: Function created with compilation errors.
    test@ORA10G>
    test@ORA10G> show err
    Errors for FUNCTION MY_FUNCTION:
    LINE/COL ERROR
    7/16     PLS-00103: Encountered the symbol "," when expecting one of the
             following:
             . ( * @ % & = - + ; < / > at in is mod remainder not rem
             <an exponent (**)> <> or != or ~= >= <= <> and or like LIKE2_
             LIKE4_ LIKEC_ between || multiset member SUBMULTISET_
             The symbol ". was inserted before "," to continue.
    test@ORA10G>
    test@ORA10G> -- the following, for example, works
    test@ORA10G> create or replace function my_function (s varchar2) return varchar2 is
      2    v_str1 varchar2(100);
      3    v_str2 varchar2(100);
      4  begin
      5    v_str1 := '*'||s||'*';
      6    v_str2 := '~'||s||'~';
      7    return v_str1||v_str2;
      8  end;
      9  /
    Function created.
    test@ORA10G>
    test@ORA10G> select my_function('xxx') from dual;
    MY_FUNCTION('XXX')
    *xxx*~xxx~
    test@ORA10G>Search this site for "pivot/pivoting/string aggregation" and you'll get a lot of examples of what you intend to do using direct sql.
    pratz
    Rephrased a bit to make the response politically correct... ;)
    Message was edited by:
    pratz

  • How to insert the records using sql query

    hi,
    i insert the record uisng sql query and DOTNET programme successfully and increase the doc num .ubut when i try to  add record using SAP B1 the old Doc no show.It means its not consider the docnums which are not inserted by sql query.
    how can i solve this problem?
    Regards,
    M.Thippa Reddy

    You are not support use Insert / Update / Delete on SAP Databases directly.
    SAP will not support any database, which is inconsistent, due to SQL-Queries, which modify datasets or the datastructure of the SAP Business One Database. This includes any update-, delete- or drop-statements executed via SQL-Server Tools or via the the query interface of SAP Business One
    Check SAP Note: 896891 Support Scope for SAP Business One - DB Integrity
    [https://websmp130.sap-ag.de/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/smb_searchnotes/display.htm?note_langu=E&note_numm=896891]

  • How to install and use sql server express 2014 with tools

    I am a student and have an assignment that requires I use either mysql or sql server, so I chose to download and install sql server express 2014 with tools, but after installation was complete all I can see is sql server 2014 import and export data (64-bit)
    and I have no clue what to do wiith it...I had used sql server 2008 a couple  of  years ago and it was easy, but this is very complicated, I have been trying to get this done for 2 days now, so someone please help me and tell me what I am doing wrong.

    Hi,
    It seems you did not installed complete software. Make sure you have downloaded below from
    SQL Server Express Download link
    Express with Advanced Services (SQLEXPRADV) when you click on Get started button on page displayed by clicking on above link. This download includes Sql Server Management Studio as well.
    Before moving I would Like you to first read
    Hardware and Software requirements
    Please refer 
    how to install SQL server 2014 express
    Above Link is for Enterprise edition  but you can use it for express as well. When you reach page feature selection please select all features to install.
    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it.
    My TechNet Wiki Articles

  • How to numberformat when using sql:query alogn with c:forEach JSTL tags

    Is there anyway to format the numeric values returned from the database when using <sql:query> alogn with <c:forEach> tags
    Here is my jsp code
    <sql:query..../>
    <c:forEach var="row" items="${queryResults.rows}">
    <tr>
    <td><c:out value="${row.COL1}" /></td>
    <td><c:out value="${row.COL2}" /></td>
    </tr>
    </c:forEach>
    Col1 values are numeric without any formats Eg: 1000, 10000, 1000000 etc.
    how can i format them to 1,000 , 10,1000 , 100,000 etc

    It is polite to mention what your answer was. These posts are not just here for you to ask questions, but to be used as a resource for other people to find answers. Saying "I solved it" with no details helps noone.
    I presume you discovered the JSTL <fmt:formatNumber> tag?

  • Update record using SQL statement

    I have VB6.0 and Oracle 10G Express Edition in Windows 2000 Server. My procedure in VB 6.0 can't update record in the table using SQL statement, and the Error Message is " Missing SET keyword ".
    The SQL statement in VB6.0 look like this :
    General Declaration
    Dim conn as New ADODB.Connection
    Dim rs as New ADODB.Recordset
    Private Sub Command1_Click()
    dim sql as string
    sql = " UPDATE my_table " & _
    " SET Name = ' " & Text3.Text & " ' " & _
    " AND Unit = ' " & Text2.Text & " ' " & _
    " WHERE ID = ' " & Text1.Text & " ' "
    conn.Execute (sql)
    Private Sub Form Load()
    Set conn = New ADODB.Connection
    conn.Open "Provider=MSDASQL;" & "Data Source=my_table;"& "User ID =marketing;" & "Password=pass123;"
    I'm sorry about my language.
    What's wrong in my SQL statement, I need help ........ asap
    Best Regards,
    /Harso Adjie

    The syntax should be
    UPDATE TABLE XX
    SET FLD_1 = 'xxxx',
    FLD_2 = 'YYYY'
    WHERE ...
    'AND' is improperly placed in the SET.

  • How do you record using a phantom mic.

    How can I record vocals in the GarageBand using the MacBook Pro?
    Thanks.

    Hi there etson!
    I have just the video for you:
    GarageBand '11 - Record your voice
    http://support.apple.com/kb/VI200
    There are other videos in the Related Videos section that may help you enhance your GarageBand experience. We also have an article online that may help you link up your third-party microphone and record from that into GarageBand:
    GarageBand '11: Record sound from a microphone
    http://support.apple.com/kb/PH1893
    Thanks for coming to the Apple Support Communities!
    Regards,
    Braden

  • How to repair database using SQL server 2008 and C#

    How to repair database in SQL server 2008 using C#
    Musakkhir Sayyed.

    Unfortunately your post is off topic as it's not specific to SQL Server Samples and Community Projects.  
    This is a standard response I’ve written in advance to help the many people who post their question in this forum in error, but please don’t ignore it.  The links I provide below will help you determine the right forum to ask your
    question in.
    For technical issues with Microsoft products that you would run into as an end user, please visit the Microsoft Answers forum ( http://answers.microsoft.com ) which has sections for Windows, Hotmail,
    Office, IE, and other products.
    For Technical issues with Microsoft products that you might have as an IT professional (like technical installation issues, or other IT issues), please head to the TechNet Discussion forums at http://social.technet.microsoft.com/forums/en-us, and
    search for your product name.
    For issues with products you might have as a Developer (like how to talk to APIs, what version of software do what, or other developer issues), please head to the MSDN discussion forums at http://social.msdn.microsoft.com/forums/en-us, and
    search for your product or issue.
    If you’re asking a question particularly about one of the Microsoft Dynamics products, a great place to start is here: http://community.dynamics.com/
    If you think your issue is related to SQL Server Samples and Community Projects and I've flagged it as Off-topic, I apologise.  Please repost your question and include as much detail as possible about your problem so that someone can assist you further. 
    If you really have no idea where to post your question please visit the Where is the forum for…? forum http://social.msdn.microsoft.com/forums/en-us/whatforum/
    When you see answers and helpful posts, please click Vote As Helpful,
    Propose As Answer, and/or Mark As Answer
    Jeff Wharton
    MSysDev (C.Sturt), MDbDsgnMgt (C.Sturt), MCT, MCPD, MCSD, MCSA, MCITP, MCDBA
    Blog: Mr. Wharty's Ramblings
    Twitter: @Mr_Wharty
    MC ID:
    Microsoft Transcript

  • How to backup database using sql query?

    Hello,i'm student, i'm researching oracle database,i want to backup database that using sql query (like backup query in SQL SERVER) ,how to do that ??
    Thank!

    No, database backups cannot be done from within the database.
    Commands for backups are outside of the database.
    See the "2 Day DBA Guide" http://download.oracle.com/docs/cd/E11882_01/server.112/e10897/toc.htm
    and the "Backup and Recovery Users's (actually Adminsitrator's) Guide : http://download.oracle.com/docs/cd/E11882_01/backup.112/e10642/toc.htm
    Hemant K Chitale

  • How to delete database using sql

    I have to delete some databases from oracle 8i. I tried it using the Database Configuration Assistant and I get stuck indefinately as the message always says connecting but nothing happens.
    How can I delete databases using sql not thru the DCA?
    Thanks

    files related to the database and follow these steps:
    1.- shutdown the database
    2.- Delete all files ( Control Files, .dbf, Redo's, Archive�s, parameter file, password file )
    3.- Delete the entrance of this database from
    listener.ora and from tnsnames.ora files.
    and that's it.
    Joel P�rez

  • Retrieving records using SQL Date Queries

    Hello,
    I am using Lab Windows CVI 8.5 and also SQL TOolkit for my project. I am using DBMapColumnToChar function for mapping Date to the database. And for retrieving records I am using SQL Query as follows:
    SELECT * FROM DBTable WHERE DATE_TABLE BETWEEN '%s' AND '%s'",cCurrentDate,cCurrentDate
    I have given a drop down for selecting dates.
    When I execute the query I am not getting the selected date values an instead I am getting some records for which the dates aren't selected...
    Quick help needed for this..Thanks in advance

    Depending on the database, the date/time structure can be completely different from the structure in CVI.  CVI uses the Windows format for time(), that is the number of seconds since 1900.  The tm struct can break this apart into a date and time structure that is usable.
    I am using MS Access for the databases and SQL toolkit.  I finally ended up replace the date field with an INT field format, and then store the CVI time (gotten with time()) as an INT value.
    Easy then to get a search range, store it a tm struct and then convert with mktime() to a calendar time to search with.
    Hope this helps.  The date/time thing is a never ending struggle.
    Regards, David E.

  • How to search records using netbeans

    i'm using netbeans.....how to search records from database
    pls help me

    Not at all....i'm familar with java,i stucking in button coding,that is
    how to match with database.
    public String buttonGo_action() throws SQLException {
    // TODO: Process the action. Return value is a navigation
    // case name where null will return to the same page.
    System.out.println("Action******");
    String sname=(String) textsearch.getText();
    sname = "%"+ sname+"%";
    grc_risks_customer_info_tableDataProvider.setCursorRow(grc_risks_customer_info_tableDataProvider.findFirst("NAME",sname));
    //.findFirst("GRC_RISKS_CUSTOMER_INFO_TABLE",sname));
    getSessionBean1().getGrc_risks_customer_info_tableRowSet().setString(1,sname);
    grc_risks_customer_info_tableDataProvider.refresh();
    this coding is not working...that's y...

  • How to Custom Report using sql server report builder for SCCM 2012 SP1

    Hi ,
    I am new to database, if i want to create a manual report using sql server report builder for SCCM 2012 SP1, what step should i take.
    i want to create a report in which computer name, total disk space, physical disk serial no come together. i already added class (physical disk serial no.) in hardware inventory classes. refer snapshot

    Hi,
    Here is a guide on how to create custom reports in Configuration Manager 2012, it is a great place to start, change to the data you want to display instead.
    http://sccmgeekdiary.wordpress.com/2012/10/29/sccm-2012-reporting-for-dummies-creating-your-own-ssrs-reports/
    Regards,
    Jörgen
    -- My System Center blog ccmexec.com -- Twitter
    @ccmexec

  • Insert a record using sql broker service

    Hi Guys,
    I need some samples to use sql broker service for creation of a record in other database in order to reduce the delay in creating number of records at the same time.

    Hello,
    In SQL Server Service Broker you can use the "Internal Activation" to start a stored procedure when a message comes in; in such a stored procedure you can do what ever you want to do, also inserting data into a table.
    See MSDN
    Service Broker Tutorials
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

  • How to create backup using sql commands

    can i create a backup using sql/sqlplus commands

    I would actually advice you to use RMAN, instead of backup using sql commands, but if you want or have a requirment to do so..
    First off all you should ensire that your databasse is in archilog mode.. (ALL PRODUCTION DATABASES should be in archivelog mode)
    you can do it using sql*plus
    archive log list
    Then if you would like to make a cold backup (the only one posible in noarchivelog mode)
    ypu have to
    shutdown immediate
    copy all database files (you don't need to copy redo logs) to another device
    startup - to startup database
    Actually I will suggest that your read User manager Recovery guide from oracle documentation
    tahiti.oracle.com
    Best Regards
    Krystian Zieja / mob

Maybe you are looking for

  • ITunes has stopped working properly.

    iTunes has stopped working properly.

  • Query condition not reflected in VC model

    Hello, I have a query that has a condition that allows the user to view the Top N of a key figure by entering the desired "N" amount. When I run the query on its own, it works as expected. If I enter 5, I see the top 5 results. I have put this query

  • Online backup for Windows and Mac

    Is there an online backup service that works with Windows and Mac and lets you use the same login? Meaning, one service, one service to pay and same login? Also, the service shouldn't bill by each desktop (as Mozy does) but instead by overall space n

  • Return STPO process

    Hi All, We have received the material from our supplying plants through STPO ( different co code) process, and done MIGO with ref to outbound delivery.  Now, I want to return the material to supplying plant .  Anyone can please tell me what i need to

  • Ipod keeps needing to be restored

    I haven't been able to synch my ipod to my computer since itunes version 7.6. Every time I connect my ipod to my computer it says that itunes detects an ipod in recovery mode and the ipod should be restored. But once I restore, itunes just keeps sayi