If I understand your question correctly then a solution for your problem is:
SELECT DISTINCT
ca.Name AS AgeGroup ,
cn.Name AS CategoryName
FROM Category AS ca
INNER JOIN Category AS parentca ON ca.ParentCategoryID = parentca.CategoryID
INNER JOIN ProductCategory AS prodca ON ca.CategoryID = prodca.CategoryID
CROSS JOIN Category AS cn
INNER JOIN Category AS parentcn ON cn.ParentCategoryID = parentcn.CategoryID
INNER JOIN ProductCategory AS prodcn ON cn.CategoryID = prodcn.CategoryID
WHERE ( parentca.Name = N'Books By Age' )
AND ( parentcn.Name = N'Kids Books' )
AND prodca.ProductID = prodcn.ProductID
ORDER BY AgeGroup ,
CategoryName
This works even if I add new pairs of data provided that I have correctly implemented your database design from your original question.
CREATE TABLE Category
(
name NVARCHAR(36) ,
parentcategoryid INT NULL ,
categoryid INT NOT NULL
)
CREATE TABLE ProductCategory
(
categoryid INT NOT NULL ,
productid INT NOT NULL,
)
INSERT category
( name, parentcategoryid, categoryid )
VALUES ( 'Books By Age', 0, 1 ),
( 'Kids Books', 0, 2 ),
( 'Young Adult', 1, 3 ),
( 'Child', 1, 7 ),
( 'Action & Adventure', 2, 4 ),
( 'Castles & Dragons', 2, 8 ),
( 'Animal Stories', 2, 9 ),
( 'Stock Exchange Adventures', 2, 10 )
INSERT ProductCategory
( categoryid, productid )
VALUES ( 3, 30891 ),
( 4, 30891 ),
( 7, 30892 ),
( 8, 30892 ),
( 7, 30892 ),
( 9, 30892 ),
( 3, 30893 ),
( 10, 30893 )
I hope this helps!
Marc
↧