我一直在为我的问题寻找解决方案,我希望你帮助我 我有一个有两列的表首先是一个名字,两个是一个小镇,我需要从Egpyt算起Sarah有多少重复,但这里是我需要的结果,如下表2所示可能
Name town
Sarah Egypt
John Germany
Mick France
Sarah Egypt
Sarah USA
John Germany
Mick France
John Germany
Name town duplicate
Sarah Egypt 1
John Germany 1
Mick France 1
Sarah Egypt 2
Sarah USA 1
John Germany 2
Mick France 2
John Germany 3
答案 0 :(得分:1)
您应该使用聚合函数count(*)和group by
select name, town, count(*) as duplicated
from my_table
group by name, town
答案 1 :(得分:0)
试试这个,
创建表格
create table test (name varchar(20), town varchar(20));
插入声明:
insert into test value('Sarah','Egypt');
insert into test values('John','Germany');
insert into test values('Mick','France');
insert into test values('Sarah','Egypt');
insert into test values('Sarah','USA');
insert into test values('John','Germany');
insert into test values('Mick','France');
insert into test values('Sarah','Egypt');
<强>查询:强>
set @x=1;
set @checkname='';
set @checktown='';
select name, town ,row_number
from ( select name, town, if(@checkname = name && @checktown = town,@x := @x + 1 ,@x := 1) as row_number,
@checkname := name, @checktown := town
from test
order by name, town
) a
答案 2 :(得分:0)
您可以使用此查询:
SET @row_number:=1;
SET @name:='';
SET @town:='';
SELECT @row_number:=CASE WHEN @name=name and @town=town THEN @row_number+1
ELSE 1 END AS row_number, @name:=name, @town:=town
FROM Table1 order by name, town;
检查SQL HERE