1

我有一个非常具体的 sql 问题。

我有一个带有订单位置的表格(每个位置都属于一个订单,但这不是问题):

|  Article ID  |  Amount  |
|--------------|----------|
|     5        |    3     |
|     12       |    4     |

对于客户,我需要对订购的每件实物进行出口,例如

|  Article ID  |  Position  |
|--------------|------------|
|     5        |    1       |
|     5        |    2       |
|     5        |    3       |
|     12       |    1       |
|     12       |    2       |
|     12       |    3       |
|     12       |    4       |

如何构建我的选择语句来给我这个结果?我认为有两个关键任务:

1)根据金额选择行X次

2) 为每篇实物文章设置位置

4

2 回答 2

6

你可以这样做

SELECT ArticleID, n.n Position
  FROM table1 t JOIN
(
   SELECT a.N + b.N * 10 + 1 n
     FROM 
    (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
   ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
) n
    ON n.n <= t.amount
 ORDER BY ArticleID, Position

注意:子查询会动态n生成从 1 到 100 的数字序列。如果您执行大量此类查询,您可能会考虑创建持久化计数(数字)表并改用它。

这是SQLFiddle演示

或使用递归 CTE

WITH tally AS (
  SELECT 1 n
  UNION ALL
  SELECT n + 1 FROM tally WHERE n < 100
)
SELECT ArticleID, n.n Position
  FROM table1 t JOIN tally n
    ON n.n <= t.amount
 ORDER BY ArticleID, Position

这是SQLFiddle演示

两种情况下的输出:

| 文章编号 | 职位 |
|-----------|----------|
| 5 | 1 |
| 5 | 2 |
| 5 | 3 |
| 12 | 1 |
| 12 | 2 |
| 12 | 3 |
| 12 | 4 |
于 2013-11-07T07:44:14.003 回答
0

询问:

SQLFIDDLE示例

SELECT t1.[Article ID],
       t2.number 
FROM Table1 t1,
     master..spt_values t2
WHERE t1.Amount >= t2.number 
AND t2.type = 'P'
AND t2.number <= 255
AND t2.number <> 0

结果:

| ARTICLE ID | NUMBER |
|------------|--------|
|          5 |      1 |
|          5 |      2 |
|          5 |      3 |
|         12 |      1 |
|         12 |      2 |
|         12 |      3 |
|         12 |      4 |
于 2013-11-08T20:39:05.307 回答