2017-01-09 107 views
1

需要與得到的查詢權幫助復位...... 我有一個表tablA有以下記錄:查詢計數,根據現場

Name, Item 
----------- 
John, Pen 
Alex, Crayon 
John, Ruler 
John, Pencil 
Bryan, Marker 
Alex, Sticker 

我需要一個查詢來 一)號記錄一個人正在爲新人重設該值。 二)按名稱排序,然後按項目

的以下結果是我會想擁有的一切:

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 

回答

1

使用另一個變量:

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 
+0

臨屋你好。那樣做了。但似乎我需要先排序。 –