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

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 SQL Query

Author  Topic 

benni-baumgaertner
Starting Member

1 Post

Posted - 2013-01-15 : 07:56:03
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
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2013-01-15 : 08:12:13
[code]
-- 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
[/code]


Too old to Rock'n'Roll too young to die.
Go to Top of Page
   

- Advertisement -