We have the following tables on our SQL Server 2012.
Table A (data):
ID, Description
---------------
1 , Bla 1
2 , Bla 2
3 , Bla 3
Table P (data):
ID, ParentID, Name
------------------
1 , NULL , AAA
2 , 3 , CCC
3 , 1 , XXX
Table X (foreign keys A_ID for A.ID and P_ID for P.ID):
ID, A_ID, P_ID
--------------
1 , 1 , 1
2 , 1 , 2
3 , 2 , 1
4 , 2 , 2
5 , 2 , 3
6 , 3 , 1
Question :
We need a request:
SELECT ...
WHERE A_ID = 1
which should return this result:
ID, Name, Subname
2 , AAA , CCC
- The name must contain the uppermost Name from table P, that is, a name that does not have a ParentID.
- The name should indicate the lowest name from table P, for which the identifier still exists in table X.
- The ID must contain the identifier from table X, where P_ID is the identifier of the lowest child.
Another example:
SELECT ...
WHERE A_ID = 2
should return this result:
ID, Name, Subname
4 , AAA , CCC
AND
SELECT ...
WHERE A_ID = 3
should return this result:
ID, Name, Subname
-----------------
6 , AAA , NULL
, " A_ID = 1", " A_ID = 2". P, , , , , .
, .
!
- , . (, P.ID '2' '4' X.P_ID '2' '4'.) , .
- P.Name .
- P ParentId .
@NEER
DECLARE @A TABLE (ID INT, DESCRIPTION NVARCHAR(10))
INSERT INTO @A
VALUES
(1 , 'Bla 1'),
(2 , 'Bla 2'),
(3 , 'Bla 3')
DECLARE @P TABLE (ID INT, ParentID INT, Name NVARCHAR(10))
INSERT INTO @P
VALUES
(1 , NULL , 'AAA'),
(2 , 3 , 'CCC'),
(3 , 1 , 'XXX')
DECLARE @X TABLE (ID INT,A_ID INT,P_ID INT)
INSERT INTO @X
VALUES
(1 , 1 , 1),
(2 , 1 , 2),
(3 , 2 , 1),
(4 , 2 , 2),
(5 , 2 , 3),
(6 , 3 , 1)