在MySQL中保持重复记录的运行记录

时间:2013-03-27 18:08:27

标签: mysql sql

有很多类似的问题要求,但我找不到办法去做我正在尝试做的事情。我需要在列中保留重复条目的运行记录,并在“所有者编号”列中报告该编号。示例如下:

Roll Number  |  Owner Name  |  Owner Number
000001       |  Patrick H.  |  1
000001       |  Paula H.    |  2
000002       |  Fred R.     |  1
000003       |  Chris P.    |  1
000003       |  Kayla A.    |  2
000003       |  Phil J.     |  3

换句话说,我只需要计算每个卷轴到目前为止有多少所有者,而不仅仅是每卷的所有者总数。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

Mysql不支持窗口函数,但可以使用变量来完成:

SET @num=0;
SET @roll='';
SELECT `Roll Number`,`Owner Name`,`Owner Number`
FROM
(
SELECT `Roll Number`,
`Owner Name`,
(CASE WHEN @roll=`Roll Number` 
                            THEN @num:=@num+1 ELSE
                            @num:=1 END) as `Owner Number`,
@roll:=`Roll Number`
FROM table1
  ) as q;

http://sqlfiddle.com/#!2/788a4/5

答案 1 :(得分:0)

您可以使用子查询或两个@variable

来执行此操作

即。 http://sqlfiddle.com/#!2/7c2fa/7

SELECT

  -- Re-selected at this level to tidy up the calculation fields
  f.rollNumber,
  f.ownerName,
  f.ownerNumber

FROM (
  SELECT

    d.rollNumber,
    d.ownerName,
    -- If the current roll number equals the previous, increment, else reset to 1
    @i := IF(d.rollNumber=@last,@i+1,1) AS ownerNumber,
    -- Sets @last to be == the "current" one for use on next row
    @last := d.rollNumber

  FROM
  (
      -- Get the raw data ordered by roll number
      SELECT

          LPAD(rollNumber,6,'0') rollNumber,
          ownerName

      FROM someTable
      -- Reorder / filter as much as you like, but always rollNumber ASC first
      ORDER BY
          rollNumber ASC,
          ownerName ASC
  ) d,(
      -- Set up the variables we will need shortly
      SELECT @i:=0,@last:=0
  ) v
) f;