查询计数并根据字段重置
Query to Count and reset based on a field
需要帮助才能正确查询...
我有一个 table tablA
包含以下记录:
Name, Item
-----------
John, Pen
Alex, Crayon
John, Ruler
John, Pencil
Bryan, Marker
Alex, Sticker
我需要查询
a) 对一个人拥有的记录进行编号,并为新人重新设置该值。
b) 按名称排序,然后按项目排序
下面的结果是我想要的:
Name, Item, Cnt
-------------------
Alex, Crayon, 1
Alex, Sticker, 2
Bryan, Marker, 1
John, Pen, 1
John, Pencil, 2
John, Ruler, 3
我在想类似的东西......(但我不知道如何在新人出现时重置 Cnt
):
select Name, Item, @cntrow: @cntrow+1 as Cnt from tablA,
(select @cntrow:=0) rx
order by Name, Item
使用另一个变量:
select
@cntrow := case when @grp <> Name then 1 else @cntrow + 1 end as Cnt,
@grp := Name as Name,
Item
from tablA
cross join(select @cntrow:=0, @grp := null) rx
order by Name, Item
需要帮助才能正确查询...
我有一个 table tablA
包含以下记录:
Name, Item
-----------
John, Pen
Alex, Crayon
John, Ruler
John, Pencil
Bryan, Marker
Alex, Sticker
我需要查询 a) 对一个人拥有的记录进行编号,并为新人重新设置该值。 b) 按名称排序,然后按项目排序
下面的结果是我想要的:
Name, Item, Cnt
-------------------
Alex, Crayon, 1
Alex, Sticker, 2
Bryan, Marker, 1
John, Pen, 1
John, Pencil, 2
John, Ruler, 3
我在想类似的东西......(但我不知道如何在新人出现时重置 Cnt
):
select Name, Item, @cntrow: @cntrow+1 as Cnt from tablA,
(select @cntrow:=0) rx
order by Name, Item
使用另一个变量:
select
@cntrow := case when @grp <> Name then 1 else @cntrow + 1 end as Cnt,
@grp := Name as Name,
Item
from tablA
cross join(select @cntrow:=0, @grp := null) rx
order by Name, Item