SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 SQL Query
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

benni-baumgaertner
Starting Member

Germany
1 Posts

Posted - 01/15/2013 :  07:56:03  Show Profile  Reply with Quote
Hello, i hope anyone can help me with a query to the following table:

id parent_id artikel_id
1 NULL 87585
2 NULL 55973
3 NULL 18753
4 2 85112
5 2 11883
6 1 25123
7 NULL 99983

The condition for the query:
1) Show all records with parent_id is NULL (that's easy) AND
2) Show only records which no other record include this id in the parent_id.
The results should show:
3 NULL 18753
7 NULL 99983

webfred
Flowing Fount of Yak Knowledge

Germany
8766 Posts

Posted - 01/15/2013 :  08:12:13  Show Profile  Visit webfred's Homepage  Reply with Quote

-- making testdata
declare @sample table(id int, parent_id int, artikel_id int)
insert @sample
select 1, NULL, 87585 union all
select 2, NULL, 55973 union all
select 3, NULL, 18753 union all
select 4, 2, 85112 union all
select 5, 2, 11883 union all
select 6, 1, 25123 union all
select 7, NULL, 99983

-- show testdata
select * from @sample

-- solution
select * from @sample as t1
where not exists(select * from @sample as t2 where t1.id = t2.parent_id)
and t1.parent_id is null



Too old to Rock'n'Roll too young to die.
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000