How To Order Data From Two Columns From Two Different Tables - sql-server

So I have a column in each table that has a numerical value and I need to order them.
The StepName is the only common value between the two tables
Table1 structure:
StepName | StepOrder
abc 10
ghi 48
jkl 62
Table2 Structure:
StepName | SubStepOrder
abc 1
abc 5
ghi 46
jkl 62
Desired Result:
StepName | Order
abc 10
abc 1
abc 5
ghi 48
ghi 46
jkl 62
jkl 62
I need the step numbers with the substep numbers ordered below them and once there are no more substep numbers we then go to the next step number with it's substepnumbers
If Step 5 had 6 substeps desired result set:
Step 1
Step 2...
...Step 5
SubStep 1...
...SubStep 6
Step 6

You just need to add an additional flag to indicate if each is a step or substep and use in an ordering criteria:
with t as (
select *, 0 substep
from t1
union all
select *, 1
from t2
)
select stepname, steporder
from t
order by stepname,substep,StepOrder

This works if you want to order just by the step order columns and not by the step name.
;WITH d (StepName, StepOrder, SubStepOrder) AS (
SELECT StepName, StepOrder, NULL
FROM t1
UNION ALL
SELECT t2.StepName, t1.StepOrder, t2.SubStepOrder
FROM t2
LEFT JOIN t1 ON t1.StepName = t2.StepName
)
SELECT d.StepName, ISNULL(d.SubStepOrder, d.StepOrder) StepOrder
FROM d
ORDER BY d.StepOrder, d.SubStepOrder
EDIT
Working example:
WITH t1 (StepName, StepOrder) AS (
SELECT 'abc', 10 UNION
SELECT 'ghi', 48 UNION
SELECT 'jkl', 62
), t2 (StepName, SubStepOrder) AS (
SELECT 'abc', 1 UNION
SELECT 'abc', 5 UNION
SELECT 'ghi', 46 UNION
SELECT 'jkl', 62
) , d (StepName, StepOrder, SubStepOrder) AS (
SELECT StepName, StepOrder, NULL
FROM t1
UNION ALL
SELECT t2.StepName, t1.StepOrder, t2.SubStepOrder
FROM t2
LEFT JOIN t1 ON t1.StepName = t2.StepName
)
SELECT d.StepName, ISNULL(d.SubStepOrder, d.StepOrder) StepOrder
FROM d
ORDER BY d.StepOrder, d.SubStepOrder

Related

SQL split values with same ID from 2 tables

I have 2 tables (that's retrieving data from a main table). Example:
Table1
id GroupX Source GroupNum Amount
-------------------------------------------------------
1 23 School SH001 1 700
2 23 Bank BA001 2 300
3 23 Music MU001 3 500
4 23 School SH999 1 900
Table2
id GroupNum SourceAmt
----------------------------------
1 23 1 700
2 23 2 100
3 23 3 500
4 23 1 900
My dilemma is with the query I'm using. It's returning additional rows for split values(notice in table 2 "GroupNum" has a split value of 700 and 900)
My results should be
id GroupX Source GroupNum Amount SourceAmt
-----------------------------------------------------------------
1 23 School SH001 1 700 700
2 23 Bank BA001 2 300 100
3 23 Music MU001 3 500 500
4 23 School SH999 1 900 900
But instead I get this
id GroupX Source GroupNum Amount SourceAmt
-----------------------------------------------------------------
1 23 School SH001 1 700 700
2 23 School SH001 1 700 900
3 23 Bank BA001 2 300 100
4 23 Music MU001 3 500 500
5 23 School SH999 1 900 900
6 23 School SH999 1 900 700
Here's my query:
SELECT
t1.id,
t1.GroupX,
t1.Source,
t1.GroupNum,
t1.Amount,
t2.SourceAmt
FROM
table1 as t1
INNER JOIN
table2 as t2 ON t1.id = t2.id
AND t1.GroupNum = t2.GroupNum
WHERE
t1.id = 23
I've tried using Distinct as well. Assistance will be greatly appreciated.
If I understand correctly, you would like to join Table1 and Table2 such that the id, GroupNum, and amounts align. If this is indeed the case, then you'll need to join on the amounts as well, e.g.,:
Select t1.id, t1.Group, t1.Source, t1.GroupNum, t1.Amount, t2.SourceAmt
From table1 as t1 INNER JOIN
table2 as t2
ON t1.id = t2.id AND t1.GroupNum = t2.GroupNum AND t1.Amount = t2.SourceAmt
where id = 23
If this is not what you want, or you would prefer not to join using the amounts (e.g., you cannot guarantee that you won't see the same amount more than once), then you're in a bit of a conundrum; you'll note that (id, GroupNum) tuples are not unique in either table, and thus your join is not one-to-one. You may want to include Source in table2 or otherwise provide a transactionId in table1 that maps onto a unique ID column in table2.
You need an additional join key. There is no obvious candidate, except perhaps for amount -- but I'm not sure that is what you intend. SQL tables represent unordered sets, so there is no concept of matching by "line number".
You can assign a row number using row_number(). The following will do the match, but you need to specify the ordering column:
Select t1.id, t1.Group, t1.Source, t1.GroupNum, t1.Amount, t2.SourceAmt
From (select t1.*,
row_number() over (partition by t1.id order by ?) as seqnum
from table1 t1
) t1 inner join
(select t2.*
row_number() over (partition by t1.id order by ?) as seqnum
from table2 t2
) t2
on t1.id = t2.id and t1.GroupNum = t2.GroupNum and
t1.seqnum = t2.seqnum
where id = 23 ;
The ? is for the ordering column in each table.
I would choose a different approach from simple INNER JOIN, simply because you can do limited things with that result set (here's the result set from that inner join)
I would do multiple joins.
First I would LEFT JOIN with the default condition + where table1.[Amount] = table2.[SourceAmt]. This will give me set where [Amount] and [SourceAmt] are equal
After this I INNER JOIN with the default condition to get the Amounts that doesn't match
Here's the query
with t1 as
(
select 23 as [id], 'School' as [Group], 'SH001' as [Source], 1 as [GroupNum], 700 as [Amount]
union all
select 23, 'Bank', 'BA001', 2, 300
union all
select 23, 'Music', 'MU001', 3, 500
union all
select 23, 'School', 'SH999', 1, 900
),
t2 as
(
select 23 as [id], 1 as [GroupNum], 700 as [SourceAmt]
union all
select 23, 2, 100
union all
select 23, 3, 500
union all
select 23, 1, 900
)
select t1.*, a.*, b.*
from t1
left join t2 as a on
t1.[id] = a.[id]
and t1.[GroupNum] = a.[GroupNum]
and t1.[Amount] = a.[SourceAmt]
inner join t2 as b on
t1.[id] = b.[id]
and t1.[GroupNum] = b.[GroupNum]
where t1.[id] = 23
And here's the result set, which you can inspect
Now, I use this result as my pre-result actually, and do a little trick with CASE and [takeIt] column, here's the final query
with t1 as
(
select 23 as [id], 'School' as [Group], 'SH001' as [Source], 1 as [GroupNum], 700 as [Amount]
union all
select 23, 'Bank', 'BA001', 2, 300
union all
select 23, 'Music', 'MU001', 3, 500
union all
select 23, 'School', 'SH999', 1, 900
),
t2 as
(
select 23 as [id], 1 as [GroupNum], 700 as [SourceAmt]
union all
select 23, 2, 100
union all
select 23, 3, 500
union all
select 23, 1, 900
),
res as
(
select t1.[id],
t1.[Group],
t1.[Source],
t1.[GroupNum],
t1.[Amount],
isnull(a.[SourceAmt], b.[SourceAmt]) as [SourceAmt],
case when a.[SourceAmt] is null or a.[SourceAmt] = b.[SourceAmt] then 1
else 0
end as [takeIt]
from t1
left join t2 as a on
t1.[id] = a.[id]
and t1.[GroupNum] = a.[GroupNum]
and t1.[Amount] = a.[SourceAmt]
inner join t2 as b on
t1.[id] = b.[id]
and t1.[GroupNum] = b.[GroupNum]
where t1.[id] = 23
)
select [id],
[Group],
[Source],
[GroupNum],
[Amount],
[SourceAmt]
from res
where [takeIt] = 1

Full Outer Join self with null values

I want to do a full outer self-join that includes nulls. For example, if the table Data looks like:
N Name Val
--------------
1 ABC 8
1 DEF 7
2 ABC 9
2 XYZ 6
(where N is a general index column to enable a self-join on sequential groups) and I do:
SELECT COALESCE(a.n, b.n) as n, COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
FULL OUTER JOIN Data b on a.N = b.N - 1 and a.Name = b.Name
I want:
N Name A B
---------------
1 ABC 8 9
1 DEF 7 NULL
1 XYZ NULL 6
but what I get is more like a cross-join:
n Name A B
--------------
1 ABC 8 9
1 DEF 7 NULL
2 ABC 9 NULL
2 XYZ 6 NULL
1 ABC NULL 8
1 DEF NULL 7
2 XYZ NULL 6
How do I perform this full outer join in order to get the condensed self-join results?
(Note: In practice column N is a generalized index, so solutions that require naming the values of N aren't practical.)
So far I've been only able to see doing this as a union. and a left and right join since the criteria of what you're after changes.
SELECT COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
LEFT JOIN Data b on a.Name = b.Name
and B.N = 2
WHERE A.N = 1
UNION
SELECT COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
RIGHT JOIN Data b on a.Name = b.Name
and A.N = 1
WHERE B.N = 2
Giving us:
+------+---+----+
| NAME | A | B |
+------+---+----+
| ABC | 8 | 9 |
| DEF | 7 | |
| XYZ | | 6 |
+------+---+----+
However this relies on a hardcoded N value which I don't think is that useful... working on better.
Since we want to handle a generalized self-join index column N let's extend the sample set a little further:
create table #Data (n int, name char(3), val int)
insert into #Data values (1, 'ABC',8)
insert into #Data values (1, 'DEF',7)
insert into #Data values (2, 'ABC',9)
insert into #Data values (2, 'XYZ',6)
insert into #Data values (3, 'ABC',9)
insert into #Data values (3, 'DEF',5)
insert into #Data values (3, 'XYZ',4)
For this sample we want the SQL to produce this output:
N Name A B
---------------
1 ABC 8 9
1 DEF 7 NULL
1 XYZ NULL 6
2 ABC 9 9
2 DEF NULL 5
2 XYZ 6 4
The following code works on the general case:
SELECT COALESCE(a.n, b.n-1) as i, COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM #Data a
FULL OUTER JOIN #Data b ON a.N = b.N - 1 AND a.Name = b.Name
WHERE a.n < (SELECT MAX(n) FROM #Data) -- Deals with end index case
OR (a.n is null AND b.n-1 IN (SELECT DISTINCT n FROM #Data))
ORDER BY COALESCE(a.n, b.n-1), Name
To see why this works, a good intermediate step is to note that when a.N = 1 we want the rows where n = 1 from:
SELECT COALESCE(a.n, b.n - 1) as n, COALESCE(a.Name, b.Name) as Name,
a.Val as A, b.Val as B
FROM #Data a
FULL OUTER JOIN #Data b ON a.N = b.N - 1 AND a.Name = b.Name
Please see the code below:
create table Data (n int, name char(3), val int)
insert into data values (1, 'ABC',8)
insert into data values (1, 'DEF', 7)
insert into data values (2 , 'ABC' , 9)
insert into data values (2 , 'XYZ', 6)
SELECT COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
FULL OUTER JOIN Data b on a.N = b.N - 1 and a.Name = b.Name
The output is this:
There are nulls on both sides.
Maybe this:
SELECT [Name]
,[1]
,[2]
FROM [table]
PIVOT
(
MAX([val]) FOR [N] IN ([1], [2])
) PVT;

How to find the cumulative sum in SubQuery? [duplicate]

declare #t table
(
id int,
SomeNumt int
)
insert into #t
select 1,10
union
select 2,12
union
select 3,3
union
select 4,15
union
select 5,23
select * from #t
the above select returns me the following.
id SomeNumt
1 10
2 12
3 3
4 15
5 23
How do I get the following:
id srome CumSrome
1 10 10
2 12 22
3 3 25
4 15 40
5 23 63
select t1.id, t1.SomeNumt, SUM(t2.SomeNumt) as sum
from #t t1
inner join #t t2 on t1.id >= t2.id
group by t1.id, t1.SomeNumt
order by t1.id
SQL Fiddle example
Output
| ID | SOMENUMT | SUM |
-----------------------
| 1 | 10 | 10 |
| 2 | 12 | 22 |
| 3 | 3 | 25 |
| 4 | 15 | 40 |
| 5 | 23 | 63 |
Edit: this is a generalized solution that will work across most db platforms. When there is a better solution available for your specific platform (e.g., gareth's), use it!
The latest version of SQL Server (2012) permits the following.
SELECT
RowID,
Col1,
SUM(Col1) OVER(ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Col2
FROM tablehh
ORDER BY RowId
or
SELECT
GroupID,
RowID,
Col1,
SUM(Col1) OVER(PARTITION BY GroupID ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Col2
FROM tablehh
ORDER BY RowId
This is even faster. Partitioned version completes in 34 seconds over 5 million rows for me.
Thanks to Peso, who commented on the SQL Team thread referred to in another answer.
For SQL Server 2012 onwards it could be easy:
SELECT id, SomeNumt, sum(SomeNumt) OVER (ORDER BY id) as CumSrome FROM #t
because ORDER BY clause for SUM by default means RANGE UNBOUNDED PRECEDING AND CURRENT ROW for window frame ("General Remarks" at https://msdn.microsoft.com/en-us/library/ms189461.aspx)
Let's first create a table with dummy data:
Create Table CUMULATIVESUM (id tinyint , SomeValue tinyint)
Now let's insert some data into the table;
Insert Into CUMULATIVESUM
Select 1, 10 union
Select 2, 2 union
Select 3, 6 union
Select 4, 10
Here I am joining same table (self joining)
Select c1.ID, c1.SomeValue, c2.SomeValue
From CumulativeSum c1, CumulativeSum c2
Where c1.id >= c2.ID
Order By c1.id Asc
Result:
ID SomeValue SomeValue
-------------------------
1 10 10
2 2 10
2 2 2
3 6 10
3 6 2
3 6 6
4 10 10
4 10 2
4 10 6
4 10 10
Here we go now just sum the Somevalue of t2 and we`ll get the answer:
Select c1.ID, c1.SomeValue, Sum(c2.SomeValue) CumulativeSumValue
From CumulativeSum c1, CumulativeSum c2
Where c1.id >= c2.ID
Group By c1.ID, c1.SomeValue
Order By c1.id Asc
For SQL Server 2012 and above (much better performance):
Select
c1.ID, c1.SomeValue,
Sum (SomeValue) Over (Order By c1.ID )
From CumulativeSum c1
Order By c1.id Asc
Desired result:
ID SomeValue CumlativeSumValue
---------------------------------
1 10 10
2 2 12
3 6 18
4 10 28
Drop Table CumulativeSum
A CTE version, just for fun:
;
WITH abcd
AS ( SELECT id
,SomeNumt
,SomeNumt AS MySum
FROM #t
WHERE id = 1
UNION ALL
SELECT t.id
,t.SomeNumt
,t.SomeNumt + a.MySum AS MySum
FROM #t AS t
JOIN abcd AS a ON a.id = t.id - 1
)
SELECT * FROM abcd
OPTION ( MAXRECURSION 1000 ) -- limit recursion here, or 0 for no limit.
Returns:
id SomeNumt MySum
----------- ----------- -----------
1 10 10
2 12 22
3 3 25
4 15 40
5 23 63
Late answer but showing one more possibility...
Cumulative Sum generation can be more optimized with the CROSS APPLY logic.
Works better than the INNER JOIN & OVER Clause when analyzed the actual query plan ...
/* Create table & populate data */
IF OBJECT_ID('tempdb..#TMP') IS NOT NULL
DROP TABLE #TMP
SELECT * INTO #TMP
FROM (
SELECT 1 AS id
UNION
SELECT 2 AS id
UNION
SELECT 3 AS id
UNION
SELECT 4 AS id
UNION
SELECT 5 AS id
) Tab
/* Using CROSS APPLY
Query cost relative to the batch 17%
*/
SELECT T1.id,
T2.CumSum
FROM #TMP T1
CROSS APPLY (
SELECT SUM(T2.id) AS CumSum
FROM #TMP T2
WHERE T1.id >= T2.id
) T2
/* Using INNER JOIN
Query cost relative to the batch 46%
*/
SELECT T1.id,
SUM(T2.id) CumSum
FROM #TMP T1
INNER JOIN #TMP T2
ON T1.id > = T2.id
GROUP BY T1.id
/* Using OVER clause
Query cost relative to the batch 37%
*/
SELECT T1.id,
SUM(T1.id) OVER( PARTITION BY id)
FROM #TMP T1
Output:-
id CumSum
------- -------
1 1
2 3
3 6
4 10
5 15
Select
*,
(Select Sum(SOMENUMT)
From #t S
Where S.id <= M.id)
From #t M
You can use this simple query for progressive calculation :
select
id
,SomeNumt
,sum(SomeNumt) over(order by id ROWS between UNBOUNDED PRECEDING and CURRENT ROW) as CumSrome
from #t
There is a much faster CTE implementation available in this excellent post:
http://weblogs.sqlteam.com/mladenp/archive/2009/07/28/SQL-Server-2005-Fast-Running-Totals.aspx
The problem in this thread can be expressed like this:
DECLARE #RT INT
SELECT #RT = 0
;
WITH abcd
AS ( SELECT TOP 100 percent
id
,SomeNumt
,MySum
order by id
)
update abcd
set #RT = MySum = #RT + SomeNumt
output inserted.*
For Ex: IF you have a table with two columns one is ID and second is number and wants to find out the cumulative sum.
SELECT ID,Number,SUM(Number)OVER(ORDER BY ID) FROM T
Once the table is created -
select
A.id, A.SomeNumt, SUM(B.SomeNumt) as sum
from #t A, #t B where A.id >= B.id
group by A.id, A.SomeNumt
order by A.id
The SQL solution wich combines "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW" and "SUM" did exactly what i wanted to achieve.
Thank you so much!
If it can help anyone, here was my case. I wanted to cumulate +1 in a column whenever a maker is found as "Some Maker" (example). If not, no increment but show previous increment result.
So this piece of SQL:
SUM( CASE [rmaker] WHEN 'Some Maker' THEN 1 ELSE 0 END)
OVER
(PARTITION BY UserID ORDER BY UserID,[rrank] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Cumul_CNT
Allowed me to get something like this:
User 1 Rank1 MakerA 0
User 1 Rank2 MakerB 0
User 1 Rank3 Some Maker 1
User 1 Rank4 Some Maker 2
User 1 Rank5 MakerC 2
User 1 Rank6 Some Maker 3
User 2 Rank1 MakerA 0
User 2 Rank2 SomeMaker 1
Explanation of above: It starts the count of "some maker" with 0, Some Maker is found and we do +1. For User 1, MakerC is found so we dont do +1 but instead vertical count of Some Maker is stuck to 2 until next row.
Partitioning is by User so when we change user, cumulative count is back to zero.
I am at work, I dont want any merit on this answer, just say thank you and show my example in case someone is in the same situation. I was trying to combine SUM and PARTITION but the amazing syntax "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW" completed the task.
Thanks!
Groaker
Above (Pre-SQL12) we see examples like this:-
SELECT
T1.id, SUM(T2.id) AS CumSum
FROM
#TMP T1
JOIN #TMP T2 ON T2.id < = T1.id
GROUP BY
T1.id
More efficient...
SELECT
T1.id, SUM(T2.id) + T1.id AS CumSum
FROM
#TMP T1
JOIN #TMP T2 ON T2.id < T1.id
GROUP BY
T1.id
Try this
select
t.id,
t.SomeNumt,
sum(t.SomeNumt) Over (Order by t.id asc Rows Between Unbounded Preceding and Current Row) as cum
from
#t t
group by
t.id,
t.SomeNumt
order by
t.id asc;
Try this:
CREATE TABLE #t(
[name] varchar NULL,
[val] [int] NULL,
[ID] [int] NULL
) ON [PRIMARY]
insert into #t (id,name,val) values
(1,'A',10), (2,'B',20), (3,'C',30)
select t1.id, t1.val, SUM(t2.val) as cumSum
from #t t1 inner join #t t2 on t1.id >= t2.id
group by t1.id, t1.val order by t1.id
Without using any type of JOIN cumulative salary for a person fetch by using follow query:
SELECT * , (
SELECT SUM( salary )
FROM `abc` AS table1
WHERE table1.ID <= `abc`.ID
AND table1.name = `abc`.Name
) AS cum
FROM `abc`
ORDER BY Name

Get a max record for each unique column value in a table

I have a database table like this
A || B || C
------------------------------------------
1 ABC 10
1 XYZ 5
2 EFG 100
2 LMN 150
2 WER 50
3 ABC 50
3 XYZ 75
Now i want to have a result set like this,where i want to have the max value of column C for each value in column A
A || B || C
-----------------------------------------
1 ABC 10
2 LMN 150
3 XYZ 75
I have tried using distinct and max() but it did not work. like this
select distinct #table.A,#table.B,MAX(#table.C) from #table group by #table.A,#table.B
Is there a simple way to achieve this?
Using MAX() as a window function:
SELECT t.A, t.B, t.C
FROM
(
SELECT A, B, C, MAX(C) OVER (PARTITION BY A) max_C
FROM yourTable
) t
WHERE t.C = t.max_C
If you want to retrieve only a single max record for each group of A values, then you should use the method suggested by #GurV, which is the row number:
SELECT t.A, t.B, t.C
FROM
(
SELECT A, B, C, ROW_NUMBER() OVER (PARTITION BY A ORDER BY C, B DESC) row_num
FROM yourTable
) t
WHERE t.row_num = 1
Note carefully the ORDER BY C, B inside the call to ROW_NUMBER(). This will place max C records at the top of each partition, and will then also order descending by B values. Only one value will be retained though.
If you order by both C and B the combination of both may or may not give you the highest value of Column C. So I feel the below query should work for your specific requirement.
SELECT table.A, table.B, table.C
FROM
(
SELECT A, B, C, ROW_NUMBER() OVER (PARTITION BY A ORDER BY C DESC) row_num
FROM yourTable
) table
WHERE table.row_num = 1
You can use window function to do this:
select * from (select
t.*,
row_number() over (partition by A order by C desc) rn
from your_table t) t where rn = 1;
If those aren't supported, use JOIN:
select t1.*
from your_table t1
inner join (
select A, max(C) C
from your_table
group by A
) t2 on t1.A = t2.A
and t1.C = t2.C;
Just an another way with a simple Join and Group BY
Schema:
SELECT * INTO #TAB1 FROM (
SELECT 1 A, 'ABC' B , 10 C
UNION ALL
SELECT 1 , 'XYZ' , 5
UNION ALL
SELECT 2 , 'EFG' , 100
UNION ALL
SELECT 2 , 'LMN' , 150
UNION ALL
SELECT 2 , 'WER' , 50
UNION ALL
SELECT 3 , 'ABC' , 50
UNION ALL
SELECT 3 , 'XYZ' , 75
)A
Do join to sub query
SELECT C2.A,C1.B, C2.MC
FROM #TAB1 C1
INNER JOIN
(
SELECT A, MAX(C) MC
FROM #TAB1
GROUP BY A
)AS C2 ON C1.A=C2.A AND C1.C= C2.MC
And the result will be
+---+-----+-----+
| A | B | MC |
+---+-----+-----+
| 1 | ABC | 10 |
| 2 | LMN | 150 |
| 3 | XYZ | 75 |
+---+-----+-----+

Return all non leaf nodes using Recursive CTE in MS SQL

I have a table with data
id name mgtId
--------------------------
1 joe null
2 jack 1
3 jill 1
4 paul 2
5 ron 4
6 sam 2
mgtId references id. How can I select non leaf nodes(joe, jack, paul) using CTE.
select *
from table
where id in (select mgtId from table)
One way:
;with parents_id as (
select distinct mgtId as id
from your_table
)
select *
from your_table t
inner join parants_id p on t.id = p.id
UPDATED 25 aprl 2012
I come to test above query and it works and also return root node:
select *
into #your_table
from (
select 1 as id, 'joe' as name, null as mgtId union all
select 2, 'jack ', 1 union all
select 3, 'jill ' , 1 union all
select 4, 'paul ' , 2 union all
select 5, 'ron ' , 4 union all
select 6, 'sam' , 2 ) T
;with parents_id as (
select distinct mgtId as id
from #your_table
)
select *
from #your_table t
inner join parents_id p on t.id = p.id
results:
id name mgtId id
-- ------- ----- --
1 joe null 1
2 jack 1 2
4 paul 2 4
with cte as(
select id,mgtId from mgr_emp
)
select b.id,b.name ,b.mgtId ,a.mgtId from cte a right join mgr_emp b
on b.mgtId =a.id

Resources