1

I have this table.

Bundles

id | parent_id | quantity
 1 | 0         | 1
 2 | 1         | 4
 3 | 2         | 5

I want to get the total quantity of a bundle with id 3, which is 1 * 4 * 5 = 20 items

Can this be done with a single query?

Tanner
  • 22,205
  • 9
  • 65
  • 83
Loupax
  • 4,728
  • 6
  • 41
  • 68

1 Answers1

3

Here's a solution using CTE:

Setup:

CREATE TABLE Table1
    (id int, parent_id int, quantity int)
;

INSERT INTO Table1
    (id, parent_id, quantity)
VALUES
    (1, 0, 1),
    (2, 1, 4),
    (3, 2, 5),
    (4, 0, 7),
    (5, 4, 10)
;

CTE to return total of id=3 and it's parent items:

;WITH myCTE AS
(
    SELECT id, parent_id, quantity
    FROM Table1
    WHERE id = 3
    UNION ALL
    SELECT T.id, T.parent_id, T.quantity
    FROM Table1 T
       JOIN myCTE C ON T.id = C.parent_id
)
SELECT EXP(sum(log(quantity))) 
FROM myCTE

Demo SQL Fiddle

Multiplication method for values in a column, SELECT EXP(sum(log(quantity))), taken from here.

Tanner
  • 22,205
  • 9
  • 65
  • 83
  • I am trying to create a CTE that will generate one row per record, with the quantity column calculated, but it gives me crazy results. What is wrong with [this](http://sqlfiddle.com/#!6/bcbbb/11) ? – Loupax Aug 08 '14 at 08:53
  • If you have a new question, you should ask it separately and link back to this one. – Tanner Aug 08 '14 at 09:04