SQL查询计算每个产品组合

时间:2015-12-15 20:05:42

标签: sql sql-server

我需要一个SQL查询来计算每个产品组合。

我有三种产品类别(游戏,配件,升级)和分配给这三类产品的产品:

+----+------------+-----------+------------+
| id | category   | product   | prod_code  |
+----+------------+-----------+------------+
|  1 | game       | GTA       |        100 |
|  2 | game       | GTA1      |        200 |
|  3 | game       | GTA2      |        300 |
|  4 | accessory  | Play Pad  |        400 |
|  5 | accessory  | Xbox Pad  |        500 |
|  6 | upgrade    | Memory    |        600 |
|  6 | upgrade    | drive     |        700 |
+----+------------+-----------+------------+

我想从每个类别中选择一种产品并制定出每一种组合:

+----+--------------+
| id | combinations |
+----+--------------+
|  1 | 100,400,600  |
|  2 | 100,500,600  |
|  3 | 100,400,700  |
|  4 | 100,500,700  |
|  ? | etc          |
+----+--------------+

我将如何做到这一点?

提前致谢,Stuart

1 个答案:

答案 0 :(得分:3)

使用CROSS JOIN

SELECT CONCAT(t1.[prod_code], ',', 
              t2.[prod_code], ',', 
              t3.[prod_code])
FROM (
   SELECT [prod_code]
   FROM mytable
   WHERE category = 'game') AS t1
CROSS JOIN (   
   SELECT [prod_code]
   FROM mytable
   WHERE category = 'accessory') AS t2
CROSS JOIN (
   SELECT [prod_code]
   FROM mytable
   WHERE category = 'upgrade') AS t3
ORDER BY t1.[prod_code], t2.[prod_code], t3.[prod_code]   
派生表的

CROSS JOIN,每个类别一个,生成以下笛卡尔积:'game' products x 'accessory' products x 'upgrade' products

Demo here