I have some hierarchical categories in SQL Server, defined as such:
CREATE TABLE [dbo].[CategoryDesc] (
[CategoryId] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](255) NOT NULL
)
CREATE TABLE [dbo].[CategoryRelationship] (
[RelationshipId] [int] IDENTITY(1,1) NOT NULL,
[CategoryId] [int] NOT NULL,
[ParentId] [int] NULL
)
CREATE TABLE [dbo].[Machine] (
[MachineId] [int] IDENTITY(1,1) NOT NULL,
[Make] [varchar](50) NOT NULL,
[Model] [varchar](255) NOT NULL,
[CreateDate] [datetime] NOT NULL,
[CategoryId] [int] NOT NULL
)
NB: Primary keys, relationships and some fields omitted for brevity.
I already use CTE’s to be able to produce a full tree, an excerpt of which outputs:
Foundry/Forging
Foundry/Forging > Core Equipment
Foundry/Forging > Furnaces
Foundry/Forging > Furnaces > Induction
Glass
Glass > Bevelling
Glass > Cutting
Glass > Cutting > Laminated Glass
Glass > Cutting > Manual
Glass > Cutting > Shape
Glass > Cutting > Straight
Glass > Decorating
Glass > Drilling
Glass > Drilling > Horizontal
Glass > Drilling > Vertical
etc
I need a query that given the top-level categoryId, returns the latest machine added (based on CreateDate) regardless of which child category and at which level it was added.
The problem I’m having is that machines may be added to either 2nd or 3rd level categories (although never the top level) and CTE’s don’t allow left joins on the recursion part.
Thanks in advance for any help given. 🙂
I have simplified your schema to:
The query you request, for root category = 1 is:
Results: