0

有很多类似的问题被问到这个问题,但我找不到一种方法来做我想做的事情。我需要在列中保留重复条目的运行记录,并在“所有者编号”列中报告该数字。下面的例子:

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

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

4

2 回答 2

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

于 2013-03-27T18:18:51.793 回答
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;
于 2013-03-27T18:19:40.883 回答