SQL Looping Index

Source: Internet
Author: User

Declare @tbl Table(order_idvarchar( -), datesdatetime)Insert @tbl(order_id,dates)Select 'A','2014-1-1' UnionSelect 'A','2014-2-1' UnionSelect 'A','2014-2-2' UnionSelect 'B','2014-1-1' UnionSelect 'C','2014-1-1' UnionSelect 'D','2014-1-1' UnionSelect 'D','2014-1-2' UnionSelect 'E','2014-12-1' UnionSelect 'E','2014-12-2' UnionSelect 'E','2014-12-3' Declare @index int,@count int,@row int,@item_order varchar( -),@current_order varchar( -)Select Identity(int,1,1) asId,order_id,dates,cast(0  as int) asRow_index into#tbl from @tbl Order  byorder_id,datesSelect @index=1,@row=1,@count=@ @rowcount while @row<=@countbegin    --First Cycle    if IsNull(@item_order,"')="'        Select     @item_order=order_id from#tblwhereId=@row    --already have to do loops    Else    begin        Select     @current_order=order_id from#tblwhereId=@row        if @current_order<>@item_order        begin            Set @index=1            Set @item_order=@current_order        End    End    --Update serial number    Update#tblSetRow_index=@index whereId=@row    Set @index=@index+1    Set @row=@row+1EndSelect *  from#tblDrop Table#tbl

SQL Looping Index

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.