Question

Just added a SQLFiddle example with comments: http://sqlfiddle.com/#!3/d1cce

I'm trying to archive to get the most main categories in a query (where Category.CategoryId = NULL)

ITEM TABLE:

  • 1 | TITLE | 2
  • 1 | TITLE2 | 3

CATEGORY TABLE:

  • 1 | Maincategory example | NULL
  • 2 | Subcategory example | 1
  • 3 | SubSubcategory example | 2

THE RESULT MUST BE:

  • 1 | TITLE | Maincategory example
  • 2 | TITLE2 | Maincategory example

Like:

select item.id, item.title (MAIN category where CategoryId = NULL) 
from .....

So as you can see I can set the Item.CategoryId to a category which is a SUBSUB category or a SUB category.

But every time I want the main category as a result in my query

How can I achieve this?

Again a example result to make myself more clear:

  • 1-Item 1-Main 2

Tables:

create table Item
(
    Id INT IDENTITY(1,1) NOT NULL,
    CategoryId INT NOT NULL,
    Title VARCHAR(80) NOT NULL,
    PRIMARY KEY (id)
)
insert into Itemvalues('Item 1', 5)

create table Category
(
    Id INT IDENTITY(1,1) NOT NULL,
    Title VARCHAR(10) NOT NULL,
    CategoryId INT,
    PRIMARY KEY (id)
)
insert into Category values('Main item 1', NULL)
insert into Category values('Sub item under Main item 1', 1)
insert into Category values('Main 2', NULL)
insert into Category values(Sub item under 2', 2)
insert into Category values('Subsub item under subitem 2', 4)
Was it helpful?

Solution

This is a good job for common table expressions which are well suited to hierarchical data structures.

;with cte as
(
  select Id as ItemId, Title as ItemTitle, CategoryId, 0 as Level
  from Item 

  union all

  select cte.ItemId, cte.ItemTitle, c.CategoryId, cte.Level + 1 as Level
  from Category c
  inner join cte on c.Id = cte.CategoryId
  and c.CategoryId is not null

)

select ItemId, ItemTitle, c.Title as CategoryTitle
from cte
inner join Category c on c.Id = cte.CategoryId
where Level = (select Max(Level) from cte as cte1 where cte1.ItemId = cte.ItemId)

SQL Fiddle demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top