-1

我想在 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 
4

3 回答 3

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;
于 2013-03-27T10:38:34.713 回答
0

您的问题已在此帖子中解决。

适应你的桌子:

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
     ;
于 2013-03-27T10:43:32.993 回答
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
于 2013-03-27T10:38:49.960 回答