SQL Server recursive CTE query to find all items belonging to all categories and their descendants

Peter Chinkin

I am a bit confused trying to use a recursive CTE to list all the items in a product catalogue for all the categories and their respective parent categories that each item belongs to.

The tables are really simple...

  • Table Category; Columns: Id, ParentID, Title
  • Table itemCategory; Columns: ItemID, CategoryID

I am just struggling to work out how to get the results I want. My best attempt is not right:

WITH
CTE (itemID, categoryID, title) AS (
    SELECT itemID, categoryID, title
    FROM itemcategory
    INNER JOIN category ON category.ID = itemcategory.categoryID
    UNION ALL
    SELECT iI.ItemID, iI.categoryID, i.title
    FROM itemcategory iI INNER JOIN category i ON i.ID = iI.categoryID
    INNER JOIN CTE ON CTE.categoryID = i.ParentID)
SELECT * FROM CTE

I have a similar query which counts the number of items under each category:

WITH cte_count_category(id, parentid, c)
        AS (SELECT c1.id,
                c1.parentid,
                (SELECT Count(*)
                    FROM   (SELECT DISTINCT itemid
                            FROM   itemcategory AS iI
                            WHERE  iI.categoryid = c1.id) AS t1) AS c
            FROM   category AS c1
            UNION ALL
            SELECT c2.id,
                c2.parentid,
                d.c
            FROM   category c2
                INNER JOIN cte_count_category d
                        ON c2.id = d.parentid)
SELECT cte_count_category.id,
        cte_count_category.parentid,
        title,
        Sum(c)     itemCount
FROM   cte_count_category
        LEFT JOIN category
                ON category.id = cte_count_category.id
GROUP  BY cte_count_category.id,
            cte_count_category.parentid,
            title
HAVING Sum(c) > 0
ORDER  BY itemcount DESC;

I just can't work out how to get it to list all the items. Any help would be appreciated.

Edit: The categories need to be n deep although it is unlikely that it will go beyond 4 levels most of the time.

The output I am looking for is one row per itemID per category it falls under so, an item in the 'music book' category would appear under both the 'music book' category and the 'book' category.

Gordon Linoff

I think the logic you need is confused by the items. You don't actually need them in the CTE (you can join them in afterwards). Alternatively, you can put them in the "base" part of the construct. Only the categories are needed in the recursive part.

This may be what you are looking for:

WITH CTE (itemID, categoryID, title, parentid, lev) AS (
      SELECT ic.itemID, c.categoryID, c.title, c.parentid, 0
      FROM itemcategory ic INNER JOIN
           category c
           ON c.ID = ic.categoryID
      UNION ALL
      SELECT cte.ItemID, c.categoryID, c.title, c.parentid, cte.lev + 1
      FROM CTE INNER JOIN
           category c
           ON CTE.ParentID = c.categoryID
     )
SELECT * FROM CTE

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Recursive CTE to find all ancestors OF ALL ITEMS

From Dev

Recursive CTE query in SQL Server

From Dev

Multiple recursive union all selects in a CTE SQL query

From Dev

Multiple recursive union all selects in a CTE SQL query

From Dev

Recursive query in SQL Server With All Childs

From Dev

Dojo query to find all descendants by class name

From Dev

SQL find all homologous categories

From Dev

How to find items with *all* matching categories

From Dev

CTE to get all children (descendants) of a parent

From Dev

Get all Magento Categories using SQL query

From Dev

The Recursive CTE to query all ancestors of a Parent-Child table is slow

From Dev

Recursive query with CTE - Concatenate all fields of child elements and add to parent

From Dev

Recursive CTE-Find all Employees Below Manager

From Dev

Recursive CTE-Find all Employees Below Manager

From Dev

Find all descendants for points in Python

From Dev

recursive cte - mark all leafs

From Dev

Recursive SQL CTE query in Pandas?

From Dev

Execution-Deferred query to identify all descendants?

From Dev

SQL query records containing all items in list

From Dev

SQL query records containing all items in list

From Dev

sql - find items that ALL users have in common

From Dev

Recursive CTE listing all ancestors as columns

From Dev

Getting all managers of the user by using CTE on SQL server

From Dev

Get all items that are past due for all employees - SQL Query

From Dev

RECURSIVE CTE SQL - Find next available Parent

From Dev

PostgreSQL find all possible combinations (permutations) in recursive query

From Dev

Creating permutation via recursive CTE in SQL server?

From Dev

SQL Server Recursive CTE - Why this behavior?

From Dev

Convert a Recursive CTE in SQL Server to netezza

Related Related

  1. 1

    Recursive CTE to find all ancestors OF ALL ITEMS

  2. 2

    Recursive CTE query in SQL Server

  3. 3

    Multiple recursive union all selects in a CTE SQL query

  4. 4

    Multiple recursive union all selects in a CTE SQL query

  5. 5

    Recursive query in SQL Server With All Childs

  6. 6

    Dojo query to find all descendants by class name

  7. 7

    SQL find all homologous categories

  8. 8

    How to find items with *all* matching categories

  9. 9

    CTE to get all children (descendants) of a parent

  10. 10

    Get all Magento Categories using SQL query

  11. 11

    The Recursive CTE to query all ancestors of a Parent-Child table is slow

  12. 12

    Recursive query with CTE - Concatenate all fields of child elements and add to parent

  13. 13

    Recursive CTE-Find all Employees Below Manager

  14. 14

    Recursive CTE-Find all Employees Below Manager

  15. 15

    Find all descendants for points in Python

  16. 16

    recursive cte - mark all leafs

  17. 17

    Recursive SQL CTE query in Pandas?

  18. 18

    Execution-Deferred query to identify all descendants?

  19. 19

    SQL query records containing all items in list

  20. 20

    SQL query records containing all items in list

  21. 21

    sql - find items that ALL users have in common

  22. 22

    Recursive CTE listing all ancestors as columns

  23. 23

    Getting all managers of the user by using CTE on SQL server

  24. 24

    Get all items that are past due for all employees - SQL Query

  25. 25

    RECURSIVE CTE SQL - Find next available Parent

  26. 26

    PostgreSQL find all possible combinations (permutations) in recursive query

  27. 27

    Creating permutation via recursive CTE in SQL server?

  28. 28

    SQL Server Recursive CTE - Why this behavior?

  29. 29

    Convert a Recursive CTE in SQL Server to netezza

HotTag

Archive