1
我想寫一個SQL查詢,生成訂單ID的,看起來像需要SQL查詢根據日期來生成訂單ID
ID SYMBOL Date OrderID
112 GR 24-Jan-13 0
112 FIX 31-Aug-11 0
112 FIX 29-Sep-11 0
112 FIX 17-Nov-11 0
112 MIN 19-Dec-08 0
112 MIN 05-Feb-09 0
445 GR 24-Jan-13 0
445 GR 25-Jul-13 0
445 FIX 31-Aug-11 0
445 FIX 29-Sep-11 0
445 FIX 17-Nov-11 0
需要輸出的數據:
ID SYMBOL Date OrderID
112 GR 24-Jan-13 1
112 GR 25-Jul-13 2
112 FIX 31-Aug-11 1
112 FIX 29-Sep-11 2
112 FIX 17-Nov-11 3
112 MIN 19-Dec-08 1
112 MIN 05-Feb-09 2
445 GR 24-Jan-13 1
445 GR 25-Jul-13 2
445 FIX 31-Aug-11 1
445 FIX 29-Sep-11 2
445 FIX 17-Nov-11 3
查詢: 我學嘗試:
;with ctes (ID, SYMBOL, date, orderid)as
(
select ID, SYMBOL, date , orderid from #temp
Union all
select m.ID, m.SYMBOL, m.date, t.orderid + 1
from ctes t
inner join #temp m on t.ID = m.id
and t.symbol = m.symbol
)select * from ctes
create table #temp (id int, SYMBOL varchar(5), [Date] datetime, orderid int)
insert into #temp (id, symbol, [date], orderid)
values(112, 'GR', '24-Jan-13', 0)
insert into #temp (id, symbol, [date], orderid)
values(112,'GR', '25-Jul-13', 0)
insert into #temp (id, symbol, [date], orderid)
values(112, 'FIX', '31-Aug-11' , 0)
insert into #temp (id, symbol, [date], orderid)
values(112, 'FIX', '29-Sep-11' , 0)
insert into #temp (id, symbol, [date], orderid)
values(112, 'FIX', '17-Nov-11' , 0)
insert into #temp (id, symbol, [date], orderid)
values(112, 'FIX', '14-Jan-13' , 0)
insert into #temp (id, symbol, [date], orderid)
values(112, 'MIN', '19-Dec-08' , 0)
insert into #temp (id, symbol, [date], orderid)
values(112, 'MIN', '05-Feb-09' , 0)
insert into #temp (id, symbol, [date], orderid)
values(112, 'MIN', '19-Aug-09' , 0)
insert into #temp (id, symbol, [date], orderid)
values(112, 'MIN', '19-Sep-13' , 0)
insert into #temp (id, symbol, [date], orderid)
values(445, 'GR', '24-Jan-13' , 0)
insert into #temp (id, symbol, [date], orderid)
values(445, 'GR', '25-Jul-13' , 0)
insert into #temp (id, symbol, [date], orderid)
values(445, 'FIX', '31-Aug-11' , 0)
insert into #temp (id, symbol, [date], orderid)
values(445, 'FIX', '29-Sep-11' , 0)
insert into #temp (id, symbol, [date], orderid)
values(445, 'FIX', '17-Nov-11', 0)
請出示你已經嘗試了什麼 - 但是,這是否來自9? – sgeddes
+1用於提供可執行示例。 –