Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

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

Starting Member

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

Flowing Fount of Yak Knowledge

8781 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 = 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  
 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.04 seconds. Powered By: Snitz Forums 2000