如何给出sql中出现的数字

时间:2013-03-27 10:13:51

标签: mysql sql

我想在sql结果中给出数字 例如,我有这样的表:

ID| Name | Login Date
1 |John  | 12/1/2013
2 |John  | 15/1/2013
3 |Ben   | 12/2/2013

现在我想要其他列来了解他们登录的时间:

ID| Name | Visit times
1 |John  |1
2 |John  |2 
3 |Ben   |1 

3 个答案:

答案 0 :(得分:1)

SELECT  t1.ID
,       t1.Name
        (
        SELECT  COUNT(t2.ID)
        FROM    tablename AS t2
        WHERE   t1.Name = t2.Name
                and t2.ID <= t1.ID
        ) AS 'Visit times'
FROM    tablename AS t1;

答案 1 :(得分:0)

看一下下面的例子。

create table log(id integer, name varchar(100), time datetime);

insert into log values (1, 'John', '2013-01-12 00:00:00');
insert into log values (2, 'John', '2013-01-15 00:00:00');
insert into log values (3, 'Ben', '2013-02-12 00:00:00');

SELECT  @row_num := IF(@prev_value=l.name,@row_num+1,1) AS RowNumber
       ,@prev_value := l.name
  FROM log l,
      (SELECT @row_num := 1) x,
      (SELECT @prev_value := '') y
  ORDER BY l.name, l.time DESC

答案 2 :(得分:0)

您的问题已在this so post中解决。

适应您的表格:

CREATE TABLE IF NOT EXIST staging_table (
      id
    , name
    , visit_sequence
)
    SELECT id
         , name
         , (
              CASE name
              WHEN @curType THEN @curRow := @curRow + 1 
                            ELSE @curRow := 1 AND @curName := name 
              END
           ) + 1 AS visit_sequence
         , login_date
      FROM your_table
         , (SELECT @curRow := 0, @curNamee := '') r
  ORDER BY name ASC
         , login_date ASC
;


ALTER TABLE your_table ADD visit_sequence INTEGER AFTER login_date;

UPDATE your_table yt
     , staging_table st
   SET yt.visit_sequence = st.visit_sequence
 WHERE st.id = yt.id
     ;