Use SQL function to get the original order number using the invoice number

Hi All,
wondering is someone can help me with this challenge I am having?  Often I need to return the original order numbers that created the resulting invoce.  This is a relatively simple seriese of joins in a query but I am wanting to simplify it using a SQL function that can be referenced each time easily from with in the SELECT statement.  the code i currently have is:
Use SQL function to get the original order number using the invoice number
CREATE FUNCTION dbo.fnOrdersThatMakeInvoice(@InvNum int)
RETURNS nvarchar(200)
AS
BEGIN
DECLARE @OrderList nvarchar(200)
SET @OrderList = ''
SELECT @OrderList = @OrderList + (cast(T6.DocNum AS nvarchar(10)) + ' ')
FROM  OINV AS T1 INNER JOIN
      INV1 AS T2 ON T1.DocEntry = T2.DocEntry INNER JOIN
      DLN1 AS T4 ON T2.BaseEntry = T4.DocEntry AND T2.BaseLine = T4.LineNum INNER JOIN
      RDR1 AS T5 ON T4.BaseEntry = T5.DocEntry AND T4.BaseLine = T5.LineNum INNER JOIN
      ORDR AS T6 ON T5.DocEntry = T6.DocEntry
WHERE T1.DocNum = @InvNum
RETURN @OrderList 
END
it is run by the following query:
Select T1.DocNum, dbo.fnOrdersThatMakeInvoice(T1.DocNum)
From OINV T1
Where T1.DocNum = 'your invoice number here'
The issue is that this returns the order number for all of the lines in the invoice.  Only want to see the summary of the order numbers.  ie if 3 orders were used to make a 20 line inovice I only want to see the 3 order numbers retuned in the field.
If this was a simple reporting SELECT query I would use SELECT DISTINCT.  But I can't do that.
Any ideas?
Thanks,
Mike

Thanks Gordon,
I am trying to get away from the massive table access list everytime I write a query where I need to access the original order number of the invoice.  However, I have managed to solve my own problem with a GROUP BY statement!
Others may be interested so, the code is this:
CREATE FUNCTION dbo.fnOrdersThatMakeInvoice(@InvNum int)
RETURNS nvarchar(200)
AS
BEGIN
DECLARE @OrderList nvarchar(200)
SET @OrderList = ''
SELECT @OrderList = @OrderList + (cast(T6.DocNum AS nvarchar(10)) + ' ')
FROM  OINV AS T1 INNER JOIN
      INV1 AS T2 ON T1.DocEntry = T2.DocEntry INNER JOIN
      DLN1 AS T4 ON T2.BaseEntry = T4.DocEntry AND T2.BaseLine = T4.LineNum INNER JOIN
      RDR1 AS T5 ON T4.BaseEntry = T5.DocEntry AND T4.BaseLine = T5.LineNum INNER JOIN
      ORDR AS T6 ON T5.DocEntry = T6.DocEntry
WHERE T1.DocNum = @InvNum
GROUP BY T6.DocNum
RETURN @OrderList 
END
and to call it use this:
Select T1.DocNum, dbo.fnOrdersThatMakeInvoice(T1.DocNum)
From OINV T1
Where T1.DocNum = 'your invoice number'

Similar Messages

  • How to use SQL functions in the queries

    hey guys i wanna know how to use SQL functions in the queries is it possible or not .

    Hi,
    Wat exactly that set values are?
    those from sql query?
    How to use count():
    The COUNT() function returns the number of rows that matches a specified criteria.
    SQL COUNT(column_name) Syntax
    The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column:
    SELECT COUNT(column_name) FROM table_name
    SQL COUNT(*) Syntax
    The COUNT(*) function returns the number of records in a table:
    SELECT COUNT(*) FROM table_name
    SQL COUNT(DISTINCT column_name) Syntax
    The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column:
    SELECT COUNT(DISTINCT column_name) FROM table_name
    The IN function helps reduce the need to use multiple OR conditions.
    The syntax for the IN function is:
    SELECT columns
    FROM tables
    WHERE column1 in (value1, value2, .... value_n);

  • Use sql function decode with Zend code

    Hi,
    I need to use sql function DECODE() in a query for PHP Code. This query works well in sql*plus but PHP returns
    the following error message:
    Parse error: syntax error, unexpected T_STRING in C:\Program Files\Zend\Apache2\htdocs\Compta\compta2.php on line 16
    the query is :
    $query =
    'select substr(c.NUM,1 ,2) Compte ,
    c.designation , a.Periode
    ,decode(substr(c.NUM,1 ,1), '1',1, '2',1,'3',1,-1) cp_type ,
    sum(credit) - sum(debit) Montant
    from ecritures a, clients b, compte c
    where
    b.NUM (+) =a.NUM
    and a.DATEECRITURE between to_date(:debut, \'dd/mm/yy\') and to_date(:fin, \'dd/mm/yy\')
    and substr(a.num,1,2) =c.num
    group by substr(c.NUM,1 ,1), substr(c.NUM,1,2) , c.designation ,a.periode
    order by compte ';
    Can any one help me ???
    Thanks by advance
    nb: Iuse Zend 2.0

    Hi,
    You need to escape single quote mark:
    decode(substr(c.NUM,1 ,1), \'1\',1, \'2\',1,\'3\',1,-1) cp_type ,
    the same way you did for to_date:
    to_date(:debut, \'dd/mm/yy\')
    Regards,
    Paweł

  • How to get the Purchase order Qty in the object dependency

    Hi,
    We are using variant pricing in the purchase order. I have condition type say u201CZVBPu201D for Pallet cost. I defined Pallet cost as 5 USD per each (pallet). I have to calculate Number of pallets = Purchase order Qty/ 5. The number of pallets should be rounded to nearest integer.
    My question is how to get the Purchase order Qty in the object dependency?
    Is there any reference table and field can be used to get Purchase order Qty just like we use MMCOM-VKOND for variant pricing.
    Appreciate your help
    Thanks,
    Srini

    Hi,
    1. I do not have system now so I can not conclusively tell about table field .
    2. Since I did it long back so I also do not exactly remember it, there are more than one place where PO qty appears for example Item overview and Item details - one of the PO qty when used in the characteristic do pull the PO qty which can be used for variant pricing (so request to please update the forum with the correct table and field once you find it - in the meantime if I get opportunity to get to system I will also try and find out ).

  • My question is Itunes related.  How do you prevent a playlist saved in Itunes from alphabetizing the song list created. I wanted to keep the original order, and somehow everything was alphabetized without requesting it.

    My question is Itunes related.  How do you prevent a playlist saved in Itunes from automatically alphabetizing the song list.   I had a specific order of songs that I wanted, and Itunes somehow automatically alphabetized them.  Is there a way to turn that feature off, and/or get them back to the original order?   I also noticed that once a playlist has been created, I cannot manually changed the order of the songs from my desktop..  Any suggestions?

    That's just the sort order. It's displaying the media alphabetically because you have clicked on the NAME column near the top of the iTunes window.
    Click on the little triangle above the column of numbers (usually on the far left side of the main iTunes window) and the media will sort in the order in which you added each item to the playlist.
    You can easily reorder songs within a playlist: Click and HOLD on the song you wish to move, then drag-and-drop it wherever you like.

  • Date Error on the Service Order while using service product

    Hi PM experts,
    I am working on the scenario resource-related billing, using service product in the service order created from a service notification linked to a contract with service product as the line item.  service product is the material of DIEN material type.
    when i was trying to save the service order created using transaction code-IW31, i am getting the  Error Message:
    " *SYS:Date 00.00.0000 not expected*".
    This error started only yesterday, and it was not there before. Basis team has confirmed that they have not done any new
    updates to the system.
    Had anyone encounered this problem before, if yes kindly let me know the solution and the steps to resolve it.
    thanks for the help.
    regards,
    rajaraman

    Hi,
    Here is the error description with message number,
    SYST: Date 00.00.0000 not expected.
    Message no. FGV004
    As an update to this thread, while searching for the reasons for the problem, i found that the characteristics used in the
    warranty class were carrying default date value as 00.00.0000.  can this be a reason for getting this error as the service
    product number which is a DIEN material type is linked to the master warranty which is in turn assigned to the equipment.
    Hope this information helps.
    regards,
    rajaraman

  • How to know the sales order closed using right click menu -Close ???

    I have an sales order with ten item, I have copied the same to delivery and before adding the Delivery I have deleted some items. After adding the Delivery, I manually closed the sales order by using the "right click menu close".
    The Open Quantity of those lines are already closed while i Close it manually.
    Now i need  a report regarding the sales orders which i  have closed manually. Any Options??

    Check the below result
    DocNum     DocDate     CardCode     CardName     Row#     ItemCode     Dscription     Price     Quantity     LineTotal
    2     2012-02-04 00:00:00.000     ED-C-102     AI HUDHA BOOK STALL     2     1010          150.000000     10.000000     1500.000000
    3     2012-02-04 00:00:00.000     ED-C-103     AL AMEEN ENGLISH SCHOOL-MANKADA     2     1011     ZINC ROD HIGH GRADE PURE ZINC 140 X 9 MM     59.790000     10.000000     597.900000
    this is the result i get while i execute your query
    but look at the db result
    DocEntry     LineNum     TargetType     TrgetEntry     LineStatus     ItemCode     Quantity     OpenQty
    1     0     15     2     C     1010     10.000000     0.000000
    2     0     15     3     C     1010     10.000000     0.000000
    2     1     -1     NULL     C     1010     10.000000     0.000000
    3     0     15     4     C     1010     1.000000     0.000000
    3     1     -1     NULL     C     1011     10.000000     0.000000
    3     2     15     4     C     1012     15.000000     0.000000
    3     3     15     4     C     1013     20.000000     0.000000
    4     0     15     5     O     1010     10.000000     5.000000
    See the last line data...it have open quantity of 5 and it also have the target type 15, If I close the sales order with docentry 4 manually using right click, the open quantity will be Zero..
    I need that last line result also as my output..
    Hope you understand my problem.
    Thank You

  • Using sql functions (min, max, avg) on varray or table collection

    Hi,
    I would like to know if there is a way to use sql function or oracle sql function like Min,Max, Avg or percentile_cont on varray or table collection ?
    Does anyone encountered this type of problem ?
    Thanks

    Yes you can apply Min,Max, Avg... if varray or table collection type is SQL (created in the databaase) UDF, not PL/SQL declared type:
    SQL> set serveroutput on
    SQL> declare
      2      type str_tbl_type is table of varchar2(4000);
      3      str_tbl str_tbl_type := str_tbl_type('X','A','D','ZZZ');
      4      max_val varchar2(4000);
      5  begin
      6      select max(column_value)
      7        into max_val
      8        from table(str_tbl);
      9      dbms_output.put_line('Max value is "' || max_val || '"');
    10  end;
    11  /
          from table(str_tbl);
    ERROR at line 8:
    ORA-06550: line 8, column 18:
    PLS-00642: local collection types not allowed in SQL statements
    ORA-06550: line 8, column 12:
    PL/SQL: ORA-22905: cannot access rows from a non-nested table item
    ORA-06550: line 6, column 5:
    PL/SQL: SQL Statement ignored
    SQL> create or replace type str_tbl_type is table of varchar2(4000);
      2  /
    Type created.
    SQL> declare
      2      str_tbl str_tbl_type := str_tbl_type('X','A','D','ZZZ');
      3      max_val varchar2(4000);
      4  begin
      5      select max(column_value)
      6        into max_val
      7        from table(str_tbl);
      8      dbms_output.put_line('Max value is "' || max_val || '"');
      9  end;
    10  /
    Max value is "ZZZ"
    PL/SQL procedure successfully completed.
    SQL> SY.

  • How to use SQL() function while writing scripts in BODS 4.0

    How to use SQL() function while writing scripts in BODS 4.0

    Hello,
    I think you want to post your question to the [Data Integration and Data Quality Management|Data Services and Data Quality; forum. This forum is for other BusinessObjects SDK development questions.
    Sincerely,
    Dan Kelleher

  • Using Aobe Photoshop Elements 6:  1.  How to download photos in the same order as on the smart card from which I downloaded them?  2.  Changing the date on each photo

    Using Adobe Photoshop Elements 6:
    1.  How can I get the 2000 photos I downloaded in the same order as on the smart card from which I downloaded them?  (This will help me label them correctly)
    2.  How can I change the date on each photo? (I want to sort by date the picture was taken, not the date it was downloaded.
    Thank you!
    Linda Berteau
    [email protected]

    You indicated that the images "seemed" to be in the right order.  It might be a good idea to rename the images on export using a custom name/sequence.  If you have done that and the images are still not in order, it's possible that your operating system browsing window is using a different sort order.  I sometimes change windows explorer to sort by file type, and then files are sometimes in what seems be a strange order.

  • Imctrying to activate my ipad. it wants me to sign in with the original apple id used to set it up. i do not know the password to the apple id and also the email used to set it up has been deactivated. can anyone help???

    I'm trying to activate my 2nd generation apple iPad. It wants me to sign in with the original apple id used to set it up. I no longer use it and don't know the password to the apple id. Also, the email used to set it up has been deactivated. Can anyone help???

    If you are trying to activate an iPad or iPhone and it is asking for a previous owners Apple ID and password, you have encountered the Activation Lock. This is a security feature that prevents thieves from setting up and using a stolen or lost iPad or iPhone. You have no alternative. You must contact the previous owner to get permission to use the device. If you cannot contact the previous owner return the device to where you bought it and get a refund. You will never be able to activate the device and no one can help you do it.
    If the Apple ID that was used on the iPad was yours originally you should be able to recover your password here:
    https://iforgot.apple.com/password/verify/appleid

  • HT4972 I want to upgrade my iOS 4 to 5 on my Ipod Touch but I no longer have the original computer I used to sync with so it keeps saying I will loose all of my apps and stuff on my new computer

    I want to upgrade my iOS 4 to 5 on my Ipod Touch but I no longer have the original computer I used to sync with so it keeps saying I will loose all of my apps and stuff on my new computer..... SO how do I tell it that my new computer is now my regular computer so that I can upgrade my iOS on it without it wiping all of my music, films and apps on it??? HELP please I am desperate to know what to do.

    http://support.apple.com/kb/HT1848 - just media purchased from iTunes Store
    Post by Zevoneer: iPod media recovery options - https://discussions.apple.com/message/11624224 - this is an older post and many of the links are also for old posts, so bear this in mind when reading them.
    Commercial software utilities for transferring songs from i-device to Mac:
    Senuti - http://www.fadingred.com/senuti/
    Phoneview - http://www.ecamm.com/mac/phoneview/
    MusicRescue - http://www.kennettnet.co.uk/products/musicrescue/ - Mac & Windows

  • I need to synch my iphone, ipod touch and classic to a Mac that I have and 2 I am about to buy. I have legally paid for all my music. If I use migration on my new Macs and clone the original, can I use my iAppliances on all 3 Macs?

    I need to synch my iphone, ipod touch and classic to a Mac that I have and 2 I am about to buy. I have legally paid for all my music. If I use migration on my new Macs and clone the original, can I use my iAppliances on all 3 Macs?

    Yes.
    You can authorize up to 5 computers to play itunes music ( pre-itunes plus).  There is no limit on itunes plus ( all itunes music for the past several years) and imported music.
    You can sync as many ipods/ipads/iphones as you like to each of your computers.

  • Can we create the Purchase order that using P&L account or just using account do not use cost center.

    Dear Experts,
    Could you please advise :
    1) Can we create the purchase order that using profit and loss account ? ( if yes , which kind of account assignment category we should use ?)
    2) How to create a purchase order for service charge .( just using GL account )
    Thanks & Best Regards,
    Watson

    Hi,
       May I know why you do not use cost center for consumption?
       You may create a new account assignment category in OME9 by copying K and maintain the cost center as optional. Please note that you have to maintain the item category blank and the account assignment category combination in OMG0. Now, you can use a GL account in PO which doesnt require a cost center assignment (in OBC4 against the field status group of the GL)
       You may use the same account assignment category created in the previous step with item category D, after you maintain the combination of the account assignment with item category D in OMG0.
        Please test the scenario and revert back.
    Regards,
    AKPT

  • How can I sort photos within an event? When I follow the Help instructions, I can sort manually in Photo format, but when I return to Event format, the original order is restored.

    How can I sort photos within an event? When I follow the Help instructions, I can sort manually in Photo format, but when I return to Event format, the original order is restored.

    Events are organisation for those who can't really be bothered. They are automatic - based entirely on Date and Time the camera records the photos as taken.
    You can move photos between Events, you can Merge Events, you can Rename them and sort them in various ways except one: You cannot manually sort in an Event as Events are all automated.
    If you want to manually sort in an Event then you've outgrown Events as an organising tool. Now it's time to look at albums (Where you can manually sort) which are much more flexible than Events as an organising tool.

Maybe you are looking for

  • Some troubleshooting videos

    Hi All, Our internal team is working on some troubleshooting videos for idea tablets. They maybe helpful for you. Check it out! Here's the list, and more to come. Lenovo IdeaPad A1-07 Does not power on after charging A2107 Cannot to 3G Internet IdeaP

  • How to get Iphone 4 backups

    Okay i have been using a windows computer for the past year and have a number backups for my Iphone 4 on it.. When i connected the iphone to my new macbook pro it asked if I wanted to update the firmware and I chose yes. When the whole thing was done

  • Zen Vision:M, Mediasource transfer problem and Digital Camera

    It used to work. Norton 360 has made a mess of lots of things... I can no longer transfer via Mediasource to my Zen Vision:M 60gb. I can view, play and rename files from Mediasource and I can transfer to the Vision:M via windows explorer (of course y

  • After upgrading to Mavericks, F14/F15 brightness adjustments don't work

    After upgrading to Mavericks, F14/F15 brightness adjustments don't work.  The screen appears to be "locked" at the dimmest brightness level.  How do I adjust the brightness?

  • IPhone 3GS menu has gone!!! Please help~ 

    Hi! Recently I bought an iPhone which version is 3.1.2. The menu in the phone was gone!!! My phone was like having a black display~ I couldn't see anything on the screen. Sometimes when I press on the Round button to enter Spotlight, one of my downlo