[英]SQL fill new column dependant on uniqueness of other columns
我在數據庫中有一個表,其中有2列名為item和slot。 我想創建另一個用數字填充的列(稱為cid),以便:
如果可能的話,我想運行一個執行該操作的SQL查詢。
根據要求編輯:
| item | slot | what cid should be
| a | x | 1
| a | y | 2
| a | y | 2
| a | z | 3
| b | x | 1
| b | y | 2
| b | q | 3
| c | x | 1
您可以通過枚舉每個項目的插槽來執行您想要的操作:
select t.*,
(@cid := if(@i = item, if(@s = slot, @cid, if(@s := slot, @cid + 1, @cid + 1))
if(@i := item and @s := 0, 1, 1)
)
) as cid
from t cross join
(select @i := -1, @cid := 0, @s := 0) param
order by item;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.