sql - subtract values of two rows and inserting it into a new column (not subsequent rows) -


relevant previous question here: how insert subtract of each 2 subsequent rows , inserting new column

i have question. in following table; want calculate amount of time have passed each user's last winning in competition. in fact should subtract last winning date current date. (place=1) indicative of winning.

the current table:

http://www.8pic.ir/images/75206897877200828586.jpg

the result want:

http://www.8pic.ir/images/78832309907063712878.jpg

i wrote following query question (according answer got previous question here) ! problem many duplicate rows! have 4000 rows, when run query 40,000 rows! problem! please me. , negative value users have not won before. want these fields null.

;with [cte15853354]  (     select          [user-name],         [submissions],         [date],         [place],         [recency],         row_number() on (order [user-name], [date] desc) [rownumber]     dbo.[top-design1]  ) select      t.[user-name],     t.[submissions],     t.[date],     t.[place],     t.[recency],     datediff(day, isnull(k.[date],t.[date]),t.[date]) [win-recency] dbo.[top-design2] [cte15853354] t left join [cte15853354] k     on k.[user-name] = t.[user-name]       k.[place]=1      order t.[user-name], t.[date] desc 

there go (and no need case testing, actually):

select [user-name],         submissions,        [date],        place,        recency,        datediff(day,         (select top(1) [date]         [top-design1] td1         td1.[user-name] = [top-design1].[user-name]         , place = 1         , [date] < [top-design1].[date]         order [date] desc), [date]) recencywin [top-design1] 

i suppose can manage use insert purposes.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -