根据列中的整数值重复结果中的行

时间:2018-11-21 12:56:12

标签: mysql sql database

我有下表。

Sales:
id      quantity    price_charged
------------------------------
101         2           100
102         3           300
103         1           120

我想选择这样的记录,使其根据数量列的值重复N行。

所以我需要以下结果

id    quantity    price_charged
--------------------------------
101     1          50
101     1          50
102     1          100
102     1          100
102     1          100
103     1          120

3 个答案:

答案 0 :(得分:1)

我认为,最好不要使用query(SQL)解决。 有一些生成功能,但是性能很差。

您必须更改模型(始终存储1个数量),或在后端处理它(java / c / stb。)

Select id, 
       1 as quantity, 
       price_charged 
from table_name t
JOIN 
(SELECT e*10000+d*1000+c*100+b*10+a n FROM
(select 0 a 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) t1,
(select 0 b 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) t2,
(select 0 c 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) t3,
(select 0 d 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) t4,
(select 0 e 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) t5) counter
ON (counter.n<=t.quantity)

联接的子查询接收的数字从0到99999,这是最大刻录数量。连接通过计数器0 ... quantity-1值重复。

答案 1 :(得分:0)

在参考了有关如何在mysql中生成序列的答案之后,我能够为我的问题提供解决方案。这是the link

SELECT
  sal.id,
  1 as quantity, sal.quantity as originalQty,
  sal.price_charged/sal.quantity
FROM
  (SELECT
     @num := @num + 1 AS count
   FROM
     sales, -- this can be any table but it should have row count 
            -- more than what we expect the max value of Sales.quantity column
     (SELECT @num := 0) num
   LIMIT
     100) ctr
  JOIN sales sal
    ON sal.quantity >= ctr.count
    order by id;

答案 2 :(得分:0)

如果有幸可以运行MySQL 8.0,则可以使用递归CTE来解决此问题。这是一种优雅的解决方案,不需要创建一系列使用变量的列表。

考虑此查询:

WITH RECURSIVE cte AS (
      SELECT 1 n, id, quantity, price_charged FROM sales
      UNION ALL
      SELECT n + 1, id, quantity, price_charged FROM cte WHERE n < quantity
)
SELECT id, quantity, price_charged/quantity quantity
FROM cte
ORDER BY id;

this DB Fiddle 中包含示例数据,查询返回:

| id  | quantity | quantity |
| --- | -------- | -------- |
| 101 | 2        | 50       |
| 101 | 2        | 50       |
| 102 | 3        | 100      |
| 102 | 3        | 100      |
| 102 | 3        | 100      |
| 103 | 1        | 120      |