如何根据另一列添加值增加的列

时间:2016-07-21 02:12:35

标签: mysql

我有一张如下表格。我想添加一个名为geom_text的列,该列应根据NumberCluster(或DriveNumber + Cluster + Date增加:

DriveNumber

所需的输出是:

Cluster         Cluster + Sub-cluster   DriveNumbe  Date
GCR_OPT_WELAC01 GCR_OPT_WELAC01         1+2         12/9/2015
GCR_OPT_WELAC01 GCR_OPT_WELAC01         1+2         12/9/2015
GCR_OPT_WELAC01 GCR_OPT_WELAC01         1+2         1/4/2016
GCR_OPT_WELAC01 GCR_OPT_WELAC01         1+2         1/4/2016
L700_NEDCC41    L700_NEDCC41            1+2+3       12/9/2015
L700_NEDCC41    L700_NEDCC41            1+2+3       16/11/2015
L700_NEDCC41    L700_NEDCC41            1+2+3       09/12/2016

2 个答案:

答案 0 :(得分:0)

您可以使用ANSI SQL窗口函数dense_rank()执行此操作:

select t.*,
       dense_rank() over (partition by cluster, drivenumber order by date) as number
from t;

MySQL不支持这些功能。相反,你可以这样做:

select t.*,
       (select count(distinct t2.date)
        from t t2
        where t2.cluster = t.cluster and t2.drivenumber = t.drivenumber and
              t2.date <= t.date
       ) as number
from t;

答案 1 :(得分:0)

set @pk1 ='';
set @rn1 =1;
set @sal ='';
set @val =1;

SELECT  dept_id,
    salary,
    denseRank
FROM
(
 SELECT  dept_id,
      salary,
      @rn1 := if(@pk1=dept_id, if(@sal=salary, @rn1, @rn1+@val),1) as        denseRank,
      @val := if(@pk1=dept_id, if(@sal=salary, @val+1, 1),1) as value,
      @pk1 := dept_id,
      @sal := salary     
  FROM
(
  SELECT  dept_id,
        salary
FROM    emp
ORDER BY dept_id,salary
) A 
) B;