根据条件分叉累积的_sum

时间:2016-02-24 04:16:37

标签: mysql sql cumulative-sum

我在mysql中有“cumul_sum”表我想根据条件划分“累积”列,即如果此列中的值为> = 70,则这些值应存储在名为“”的新列中其他“并且应该在它前面存储相应的sku_id,这是mytable的结构

sku_id   cumulative
  1         10
  20        20
  13        30
  24        50
  9         80 
  4         100

这就是我所期待的

sku_id    cumulative    sku_id_1    others
 1           10            9         80
 20          20            4         100 
 13          30
 24          50


Is this any way possible

如果是,请帮忙 提前致谢

2 个答案:

答案 0 :(得分:1)

我不确定您要实现的目标是高效且可扩展的,但这可能会起作用。

SET @row = 0;
SET @row2 = 0;
SELECT (@row:=@row+1) AS row, 
        sku_id, 
        cumulative, 
        s.sku_id_1 as 'sku_id_1', 
        s.others as 'others'
FROM `cumul_sum`
LEFT JOIN (SELECT (@row2:=@row2+1) AS 'row', 
           sku_id AS 'sku_id_1', 
           cumulative as 'others'
           FROM `cumul_sum`
           WHERE `others` >= 70) s ON `cumul_sum`.`row` = `s`.`row`
WHERE `cumul_sum`.`cumulative` < 70;

答案 1 :(得分:1)

这看起来不像sql查询的工作,而是应该在UI中处理该格式。

所以只需创建两个查询。

SELECT sku_id, comulative
FROM YourTable
WHERE comulative < 70 

SELECT sku_id, comulative as others
FROM YourTable
WHERE comulative >= 70 

如果你在php或类似的东西上显示(这不是真正的代码)

$size1 = query1.length;
$size2 = query2.length;
if ($size1`> $size2)
    $total = $size1
else 
    $total = $size2

<table>
for ($i = 1 to $total)
{
   <tr>
       <td> if ($i <= $size1) echo $query1[$i]; </td>
       <td> if ($i <= $size2) echo $query2[$i]; </td>
   </tr>
}
</table>