Author |
Topic |
henryvuong
Starting Member
8 Posts |
Posted - 2014-07-05 : 23:54:22
|
I have a Categories table and Items table like these:Categories CategoryID CategoryName CategoryLevel OrdinalNumber1 All 0 12 iOS 1 23 Android 1 54 Sub iOS 1 2 35 Sub Andoid 1 2 66 Others 1 87 Sub Andoid 2 2 78 Sub iOS 2 2 4 Items ItemID ItemName CategoryID1 iPhone 5 42 Motorola Droid 53 iPad 2 84 Samsung S1 75 iPhone 4 46 iPad Air 87 Samsung S3 78 Dell Laptop 6 As you can see, they can be join by CategoryID. The Categories table, if sorted by OrdinalNumber and CategoryLevel, has tree-view display: CategoryID CategoryName CategoryLevel OrdinalNumber1 All 0 12 iOS 1 24 Sub iOS 1 2 38 Sub iOS 2 2 43 Android 1 55 Sub Andoid 1 2 67 Sub Andoid 2 2 76 Others 1 8 Now I need an SQL command that can display all items belong to a category and its subcategories. For example, if I choose CategoryID=2 I will get:iPhone 5iPad 2iPhone 4iPad AirIf I choose CategoryID=3 I will get:Motorola DroidSamsung S1Samsung S3If I choose CategoryID=6 I will get:Dell LaptopAnd if I choose CategoryID=1 I will get all items. I am thinking of using Common Table Expression but can not figure out how to do it. |
|
stepson
Aged Yak Warrior
545 Posts |
Posted - 2014-07-06 : 04:54:34
|
[code]DECLARE @iCateg AS INTSET @iCateg = 2--SET @iCateg = 3--SET @iCateg = 6--SET @iCateg = 1;with Categories(CategoryID,CategoryName,CategoryLevel,OrdinalNumber)AS ( SELECT 1,'All',0,1 UNION ALL SELECT 2,'iOS',1,2 UNION ALL SELECT 3,'Android',1,5 UNION ALL SELECT 4,'Sub iOS 1',2,3 UNION ALL SELECT 5,'Sub Andoid 1',2,6 UNION ALL SELECT 6,'Others',1,8 UNION ALL SELECT 7,'Sub Andoid 2',2,7 UNION ALL SELECT 8,'Sub iOS 2',2,4),Items (ItemID,ItemName,CategoryID)AS (SELECT 1,'iPhone 5',4 UNION ALL SELECT 2,'Motorola Droid', 5 UNION ALL SELECT 3,'iPad 2',8 UNION ALL SELECT 4,'Samsung S1',7 UNION ALL SELECT 5,'iPhone 4',4 UNION ALL SELECT 6,'iPad Air',8 UNION ALL SELECT 7,'Samsung S3',7 UNION ALL SELECT 8,'Dell Laptop',6 ),RecCategoriesAS( SELECT C.CategoryID ,C.OrdinalNumber ,C.CategoryLevel FROM Categories AS C WHERE C.CategoryID = @iCateg UNION ALL SELECT C.CategoryID ,C.OrdinalNumber ,C.CategoryLevel FROM RecCategories AS RC INNER JOIN Categories AS C ON RC.OrdinalNumber + 1 = C.OrdinalNumber AND ((RC.CategoryLevel <= C.CategoryLevel) OR (select CategoryLevel from Categories where CategoryID = @iCateg) = 0) )SELECT I.ItemName FROM Items AS I WHERE I.CategoryID IN (SELECT RC.CategoryID FROM RecCategories AS RC)[/code]sabinWeb MCP |
|
|
|
|
|