How can i get the id of the last child record in hierarchical data

I want to get the lastest child record  of the parents like 
the result   
If I Select A then the result should be  'C' , 'E' , 'F' , 'G'
If i select D then the result should be 'F' etc
Thanks
USE [SMEDB]
GO
/****** Object:  Table [dbo].[Table_3]    Script Date: 11/26/2014 2:10:49 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Table_3](
[ID] [nvarchar](50) NULL,
[ParentID] [nvarchar](50) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[Table_3] ([ID], [ParentID]) VALUES (N'A', NULL)
INSERT [dbo].[Table_3] ([ID], [ParentID]) VALUES (N'B', N'A')
INSERT [dbo].[Table_3] ([ID], [ParentID]) VALUES (N'C', N'D')
INSERT [dbo].[Table_3] ([ID], [ParentID]) VALUES (N'D', N'A')
INSERT [dbo].[Table_3] ([ID], [ParentID]) VALUES (N'E', N'D')
INSERT [dbo].[Table_3] ([ID], [ParentID]) VALUES (N'F', N'E')
INSERT [dbo].[Table_3] ([ID], [ParentID]) VALUES (N'G', N'A')

WITH cte(ID, ParentID, Lvl, HPath)
AS (
       SELECT ID,
              ParentID,
              0,
              CAST(ID AS VARCHAR(MAX)) + '\' AS HPath
       FROM   dbo.[Table_3]
       WHERE  ID ='D'
       UNION ALL
       SELECT        e.ID,
                     e.ParentID,
                     m.Lvl + 1 AS Lvl,
                     m.HPath +CAST(e.ID AS VARCHAR(MAX))+ '\'  AS HPath
       FROM          dbo.[Table_3] AS e
       INNER JOIN    cte AS m ON m.ID = e.ParentID
),cte1
AS
SELECT HPath,id,Parentid,lvl,
RIGHT(LEFT(HPath,LEN(HPath)-1),CHARINDEX('\',REVERSE(LEFT(HPath,LEN(HPath))))) lst
FROM   cte WHERE lvl>0
) SELECT lst FROM cte1 WHERE NOT EXISTS (SELECT * FROM cte1 c WHERE c.ParentID=cte1.lst)
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence

Similar Messages

  • How can I get the last / newest record of a table?

    Hi,
    I am developing an ecard app that has a create greeting page, a preview page with edit and send buttons and an edit page.
    I got he insert working, and on the preview page I created a master record page (displays all records), and delete all unecessary designs. Doing it this way also gives me the 'edit' button, so people are able to edit their page.
    How do I get only the last record displayed though? At the moment it loops through all records and displays them in sets of 10. I found the variable that holds the totla count of records ('$totalRows_rs7417_content1'), but how do I (re-)write the script so it ONLY diplays the last record?
    I need to get the ID of this record as I am writing this into the PARAMs of the object and embed tags of my message .swf (this picks up the ID and based on that sucks the greetings text out of the database via another php script.
    Also, from this page, how can I send an email to the sender (ie creator of the message) as well as the recipient? Both email addresses are in the databse so should be part of the erecord returned.
    Thanks,
    Nik

    -----
    OK, So how do I recreate what I got in a non-ADDT list?
    well, when you´re just about to display one certain record, the term "list" is somewhat inappropriate anyway.
    What you´d simply need to do IMHO, is using DW´s native functions to create the basic "SELECT * FROM table_name ORDEr BY ID DESC" query, add "LIMIT 1" manually, and display the desired "dynamic text" placeholders in 1 table cell -- don´t think there were any need for all the fancy stuff
    (sorting, filtering etc) provided by ADDT´s list, as it´s just 1 record.
    It also occurred to me just now that finding the last record that has been added *may-* notbe enough if the site gets used a lot by our executives (I am thinking of a situation where 2 or three peolpe create greetings at the same time and press submit and then getting each others messges rather than their own).
    in this case you might want to additionally store the respective executive´s "kt_login_id" session variable -- because it´s this unique "identifier" which should be used to show the last inserted record of the person who actually inserted it, means adding a "WHERE submitter_id" equals the session variable kt_login_id - clause to the query.
    When creating a non-ADDT list that´s at some point based on detecting a user session, you´ll BTW need to insert at line 1
    I can't seemt o insert it on the page as it is looking for a insert, update or delete bahaviour on the page which of course I don't have
    please search these forums for several posts I made which explain my "use dummy table" approach that´s made for cases when you actually don´t have anything to insert/update/delete, but need "something" for ADDT´s send email behaviours.
    Cheers,
    Günter Schenk
    Adobe Community Expert, Dreamweaver

  • How can I get the last updated email address of the customer ??

    Dear All,
    Please let me know, How can I get the last updated email address of the customer ??
    Also, I am trying to read CDHDR table where OBJECTCLAS is ADRESSE, however what value should be passed into OBJECTID field, looks like it is ADRNR with a Suffix BP.
    Please confirm me what value should be passed into OBJECTID field.
    Thank you.
    Anitha

    Hi Anitha,
      Check if this is something that helps you:
    Change documents in BAS
    CDHDR
    address type 1
    objectclass = ADRESSE             
    objectid = addrgroup + addrnumber     (ADRC-ADDR_GROUP + ADDRNNUMBER) !!
                     'BP  000xxxxxx'
    private address (address type 2)
    objectclass = ADRESSE2
    objectid =  'BP  000xxxxxx000yyyyyyy'   
                            persnumber+adrnr private
    address type 3
    objectclass = ADRESSE3
    objectid =  'BP  000xxxxxx000zzzzzzz'
                              persnumber +comp.address
    The above details is from the link: http://wiki.sdn.sap.com/wiki/display/ERPLO/LO-MD-BP
    Regards,
    Swarna Munukoti

  • I have an Ipod touch updated to last available ios 4.2.1. How can I get the last compatible versions of the apps?

    I have an Ipod touch updated to last available ios 4.2.1.
    How can I get the last compatible versions of the apps?
    In the appstore there are only the lat app versions, most of them are incompatible with my device.
    I know that previous versions of these apps were compatible with my ipod.
    Can all download them someway?
    thanks

    The problem is: I never had the compatible versions. But I want them, I'd buy them if I could.
    So I'm stuck with my Ipod, which can't be upgraded anymore to higher IOS versions, and with the appstore, that does not offer older versions; versions that have existed and still exist, perhaps in the recycle bin of some users, or somewhere in the appstore servers.
    I know, its a policy, just to sell more devices. Will not work with me. I'm not buying more Ipods

  • Please help.........how can i get the last date of the month?????

    Hello....
    I want to get the last date of the month.
    For example, the last date of Jan is 31.
    How can I get the last date of the particular month and year ????
    Thanks for help.
    Gloria

    Hi Gloria
    1. How can I compare the date???date1.compareTo(date2)
    where date1 and date2 is a java.util.Date Object
    will return 0 if it is the same date
    or
    date1.after(date2)
    where date1 and date2 is a java.util.Date Object
    will return true if date1 is after date2
    (the same for date1.before)
    2. How can I change the date format into yyyymmdd format???? I just want the year, month and date.try the java.text.SimpleDateFormat Object
    new SimpleDateFormat("yyyymmdd").format(yourdate)
    Hope this help.
    Please also have a look at a calendar I wrote, (maybe it help)
    demo & source :
    http://www.geocities.com/globe_software/java/components/
    globe_sa

  • How can i get the lasted vision of visual administrator

    HI:
    when i connet j2ee engine,i get the system warning:
    "visual administrator vision is older than the version of j2ee engine kernel: ..."
    how can i get the lasted vision of visual administrator?

    Get your portal administrator to copy the j2ee/admin from the server you're trying to connect to.  You can then install and run it from your local hard drive.

  • Different ways to get the last 5 records ordered by date

    I have a query no that returns the tickets ordered by moddt, modification date,
    I was thinking of adding a select on top, to get the last 5 records of that list the select already generates. An other way was to use that select to create a view,
    and get the 5 last records that way. I also though of a possibly impossible cursor with a sequence, but hmm well I consider that not a good solution.
    So I'm trying to find a way, using a select, the topmost select which is not completed yet, to get the last 5 records. Maybe I should just try the rownumber thing again or something likewise.
    Select * from(
    select * from(
    Select ticketid, appliecatiecd, categorieid, substr(titel,&,200)||' ...' "titel", klantproriteitid, interneprioriteitid,
    (select g.voornaam||' '||g.naam
    from gebruiker g
    Where g.gebruikerid = t.gebruikerid
    And t.applicatiecd = NVL(:P0_applicatiecd, :F101_applicatiecd))"aangemaakt door",
    (select s.statusdefoms "status"
    From status s
    Where s.statusid = t.statusid
    And t.applicatiecd = NVL(:P0_applicatiecd, :F101_applicatiecd)) "status",
    Versieid,
    Moddt,
    Row_number() over (order by ticketid desc) rn
    From ticket t
    Where applicatiecd = NVL(:P0_applicatiecd, :F101_applicatiecd) )
    Order by moddt)
    Where --

    Hi Floris,
    You can also use RANK: http://www.dba-oracle.com/oracle_news/oracle_faq/faq_beg_sql_top_n_rows.htm
    Regards Pete

  • How can I get the last 18 numbers from this string

    Hi,
    I'm querying this field from a table. How can I only get the last 18 numbers:
    The numbers look like this:
    500000000818118

    If it is always the last 18 numbers just use the Right() function.  Examples:
    Right("500000000818118", 18)
    or
    <cfset mystring = "500000000818118">
    <cfset mynewstring = Right(mystring, 18)>
    or
    #Right(yourquerycolumn, 18)#
    etc.
    Edit:
    Well I just noticed that your example string is only 15 characters long.  Perhaps I mis-understood your question?
    Message was edited by: Miguel-F

  • How can I get the "Multi-Camera Record" button to show up in the Multi-Camera editor?

    I've used the Multi-Camera editor in Premiere for years but in the most recent update (Adobe Premiere Pro CC 2014) I can't get the Multi-Camera Editor to record my camera switches. I looked for the Multi-Camera Record button but it wasn't where it used to be, and even when hitting the plus sign to add more buttons it does not appear in that menu either.
    What am I missing here? Please help. Thank you.

    Did you try it in the program monitor?

  • How can i get the last delete picture's info from tlf?

    if i delete the picture from the tlf i can't make the tlf undo
    and I want to get the picture'info with I last time delete from tlf 

    Can you let us know what you are doing to delete the picture, and also how you are undoing it? If it is being deleted through the EditManager delete function, the delete should undo correctly. Some example code to illustrate the problem would help.
    Once the picture has been deleted, TLF has no further reference to it. If you want to keep a reference, you will have to get it before it has been deleted. If you don't have control over the delete, you could find out when the image is deleted by listening for FLOW_OPERATION_END events.
    - robin

  • How can I get the last known IP address of my stolen iPad?

    My iPad 16G Wifi was stolen with Find My iPhone turned on. It was broadcasting some coordinates yesterday, but the accuracy was not the best. Can I somehow get the IP address for this last online point? It would help to filter out some apartments in the building it was located.

    Sorry, but no. The Find My iPhone app is the only way to "locate" an iOS device.
    Reporting a lost or stolen Apple product

  • How can I get the start and end of a date range?

    Post Author: RobR
    CA Forum: Formula
    Greetings!
    I have a report whose records are selected if a date field is within the date range returned by the LastFullWeek function.  I want the header for that report to print the first and last dates in that range.  I don't see a way to extract those dates from a date range.  How do I do it?
    Also, I think it would be nice to be able to walk through a date range using a for loop, something along the lines of the following:
    for (thisDate in LastFullWeed)(    do something;)
    but I didn't see syntax like that in the help system.  If I could do this, then I could get the first and last date.  Is this possible?
    Thank you!
    RobR

    Post Author: SKodidine
    CA Forum: Formula
    If all you want is the starting date and ending date of the function LastFullWeek, then all you have to do is this:
    minimum(LastFullWeek) & '          ' & maximum(LastFullWeek);
    On a side note, from your post: for (thisDate in LastFullWeed)  Whatcha smokin'  Willis?? 

  • [JS][CC] How can I get the last visible character in an overflowed Text Frame?

    Hello
    I'm new in InDesign scripting in javascript. I would like to know if there is a way to get the position of the last character in a Text Frame that is overflowed? I need this because I want to calculate how many characters are hidden (overflowing text) via script.
    I've searched in the forums about this but what I find is always a script for alerting if there's overset text or not.
    I'd really appreciate any help!

    Well, let's say that myFrame is an overflowing text frame.
    So, the last character in that frame would be
    myFrame.characters[-1];
    To calculate the number of overflowing characters, select the
    overflowing text frame, and run this script:
    myFrame = app.selection[0];
    myParentStory = myFrame.parentStory;
    alert("Number of overflowing characters is
    "+myParentStory.characters.itemByRange(myFrame.characters[-1],
    myParentStory.characters[-1]).length-1);
    Ariel

  • How can I get the last occurrence of a repeated item in Numbers

    Hi everyone, I'm hoping this question has a straightforward answer.
    I have a simple 2-column table (Table 1). Column A is a list of names. Column B is a list of dates where those names have had appointments. (Most names in Column A are repeated because they have had multiple appointments).
    I'd like to create an automated table based Table 1 that lists each name from Column A only once, with the last appointment that each person has had.
    Any ideas, I'd be grateful.
    Thanks!

    Hi Paul,
    Late to the party, as I was called to dinner shortly after starting on a solution and wasn't able to get back to it for a few hours.
    This was worked out in Numbers '09 (v2.3), but the formulas should work as well in Numbers 3. The solution requires the data on the Data table to be entered (or sorted) in ascending order of dates. Dulicate dates, though not included in the example, should not create an issue.
    The added column (Name index—column C) may be hidden. It is needed to mark the first occurrence of each name, and required only if you want the name list in column A of the summary table (Most recent appointment) filled automatically.
    Formulas:
    Data::C2, and filled down to the end of column C: =IF(COUNTIF($A$2:A2,A)=1,MAX($C$1:C1)+1,"")
    COUNTIF($A$2:A2,A) counts the number of occurences of the name in the same row as the formula from row 2 of column A to the row containing the formula. IF that count is 1, the number of the row is placed in the cell, otherwise the cell receives a null string ( "" ).
    Most recent appointment table:
    A2, and filled down to end of column A:
    =IF(ROW()-1>MAX(Data :: C),"",OFFSET(Data :: $A$1,MATCH(ROW()-1,Data :: $C,0)-1,0))
    If the row number minus 1 is greater than the number of distinct names in the index column, a null string is placed in the cell. Otherwise, the OFFSET function uses MATCH to determine the row in which to find the next name (in order of first appearance) and places that name in its cell.
    B2 and filled down: =IF(LEN(A)>0,LOOKUP(A,Data :: $A,Data :: $B),"")
    IF here uses LEN() to determine if there is data (a name) in column A. If so, then LOOKUP looks up the name in column A of the Data table and returns the date from the same row of column B. If there's no data (name) in column A, IF places a null string in the cell.
    This formula takes advantage of the fact that LOOKUP searches from the bottom of the column, and returns the result from the first match it finds.
    Regards,
    Barry

  • How can i get the last 2 months history?

    I want to get the call history of the last 2 months. Unfortunatelly iphone restore only the last 100 phone calls. Is there a way to retrive all phone calls from the last 2 months?

    The best way is to contact your carrier for an itemised bill.

Maybe you are looking for

  • Download to excel in different tabs from bsp page

    Hi all, I have a requirement in which I have to download to xl-sheet in different tabs based on some conditions from a bsp page. I am successful in downloading data into different tabs. Now I had written the piece of code required to download to xl i

  • Phone problems

    Hi I'm having problems with my pearl 8100 phone will ring and call out but when it says connected I can't hear anyone nor do I hear peoples phone ringing when I call them, I've talked to the people i've called and their phone does ring but they can't

  • What exactly do I do next?

    I'm just trying to re-install one of my 80 or so apps (which I uninsatlled on the iPad) by using iTunes. But after connecting the iPad and PC I get this message: I haven't a clue how I'm supposed to proceed. Of course there are several apps on my iPa

  • Regardingtest configuration issuse

    when i test the configuration test , i am getting this error. Runtime exception occurred during application mapping com/sap/xi/tf/_MM_RAS_; com.sap.aii.utilxi.misc.api.BaseRuntimeException:Premature end of file. M.S

  • Premiere Pro CC crashing seconds after opening

    Lately my Premiere Pro CC program has been crashing virtually as soon as I open it and displaying this message: Sometimes the message is displayed before the program is fully opened and sometimes it doesn't happen until I try to perform a basic actio