Quantcast
Channel: dBforums – Everything on Databases, Design, Developers and Administrators
Viewing all articles
Browse latest Browse all 13329

SQL Challenge: Numeric Combinations

$
0
0
I've been working with some interesting data puzzles recently and it got me thinking of some little challenges to try and solve in T-SQL.

So here's one:
Code:

DECLARE @x table (
  id    int
 , price money
)

INSERT INTO @x (id, price)
  VALUES (1, 1.0)
      , (2, 1.0)
      , (3, 1.0)
      , (4, 1.5)
      , (5, 1.5)
      , (6, 2.0)
      , (7, 2.5)
      , (8, 2.5)
      , (9, 3.5)

DECLARE @target money = 3.0

/*
  Aim: find all combinations of items that when
      added together equal the target amount.

  Expected results if @target = 2.5:
      1, 4
      1, 5
      2, 4
      2, 5
      3, 4
      3, 5
      7
      8

  Expected results if @target = 3.0:
      1, 2, 3
      1, 6
      2, 6
      3, 6
      4, 5

  Expected results if @target = 3.5:
      1, 2, 4
      1, 3, 4
      2, 3, 4
      1, 2, 5
      1, 3, 5
      2, 3, 5
      4, 6
      5, 6
      1, 7
      1, 8
      2, 7
      2, 8
      3, 7
      3, 8
      9
*/

I'm stumped on how to approach this one, any ideas?

Good luck!

Viewing all articles
Browse latest Browse all 13329

Trending Articles