0

ID と TIMESTAMP を含むログのテーブルがあります。ID で ORDER BY、次に TIMESTAMP で ORDER したい。

たとえば、結果セットは次のようになります。

12345   05:40   
12345   05:50   
12345   06:22   
12345   07:55   
12345   08:33   

それが完了したら、3 番目の列に順序の値を挿入して、グループ内で最も古いものから最も新しいものへの配置であることを示します。

したがって、次のようなものになります。

12345   05:40   1 <---First entry
12345   05:50   2
12345   06:22   3
12345   07:55   4
12345   08:33   5 <---Last entry

SQLステートメントでそれを行うにはどうすればよいですか? データと ORDER BY ID、TIMESTAMP を選択できます。しかし、グループ化に基づいて注文値を挿入できないようです。:(

4

3 に答える 3

3

update ではなく これを試してくださいinsert

フィドルのデモはこちら

;with cte as(
  select id, yourdate, row_number() over(order by id,yourdate) rn
  from yourTable
)
Update ut Set thirdCol = rn
From yourTable ut join cte on ut.Id = cte.id and ut.yourdate = cte.yourdate

注: ID ベースごとに更新する必要がある場合はthirdColumn、次を使用して行番号を分割してください。row_number() over (partition by id, order by order by id,yourdate)

結果:

|    ID | YOURDATE | THIRDCOL |
|-------|----------|----------|
| 12345 |    05:40 |        1 |
| 12345 |    05:50 |        2 |
| 12345 |    06:22 |        3 |
| 12345 |    07:55 |        4 |
| 12345 |    08:33 |        5 |
于 2013-10-15T14:45:01.900 に答える
1

派生テーブルと更新を使用します。

IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL
begin
        drop table #TableOne
end


CREATE TABLE #TableOne
( 
SomeColumnA int , 
LetterOfAlphabet varchar(12) , 
PositionOrdinal int not null default 0 
)




INSERT INTO #TableOne ( SomeColumnA , LetterOfAlphabet )
select 123 , 'x'
union all select 123  , 'b'
union all select 123  , 'z'
union all select 123  , 't'
union all select 123  , 'c'
union all select 123  , 'd'
union all select 123  , 'e'
union all select 123  , 'a'

Select 'pre' as SpaceTimeContinium , * from #TableOne order by LetterOfAlphabet

Update 
#TableOne
Set PositionOrdinal = derived1.rowid
From 
( select SomeColumnA , LetterOfAlphabet , rowid = row_number() over (order by LetterOfAlphabet asc)  from #TableOne innerT1  ) 
as derived1
join #TableOne t1
    on t1.LetterOfAlphabet = derived1.LetterOfAlphabet and t1.SomeColumnA = derived1.SomeColumnA


Select 'post' as SpaceTimeContinium, * from #TableOne order by LetterOfAlphabet


IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL
begin
        drop table #TableOne
end
于 2013-10-15T14:46:03.577 に答える