与我之前提出的问题相关:how to insert subtract of each two subsequent rows and inserting it into a new column
我有另一个问题。在下表中;我想计算每个用户上次参加比赛的时间。事实上,我应该从当前日期减去最后一个获胜日期。 (地方= 1)表示获胜。
当前表:
http://www.8pic.ir/images/75206897877200828586.jpg
我想要的结果:
http://www.8pic.ir/images/78832309907063712878.jpg
我为这个问题写了以下查询(根据我之前的问题here给出的答案)!但问题是我得到了很多重复的行!我只有4000行,但是当我运行这个查询时,我得到40,000行!问题是什么!你能帮我吗?而且我对以前没有赢过的用户也有负面价值。我希望这些字段为NULL。
;WITH [cte15853354] AS
(
SELECT
[user-name],
[submissions],
[date],
[place],
[recency],
ROW_NUMBER() OVER (ORDER BY [user-name], [date] DESC) AS [ROWNUMBER]
FROM dbo.[top-design1]
)
SELECT
t.[user-name],
t.[submissions],
t.[date],
t.[place],
t.[recency],
DATEDIFF(DAY, ISNULL(k.[date],t.[date]),t.[date]) AS [win-recency]
INTO dbo.[top-design2]
FROM [cte15853354] t
LEFT JOIN [cte15853354] k
ON k.[user-name] = t.[user-name]
where k.[place]=1
ORDER BY t.[user-name], t.[date] DESC
答案 0 :(得分:1)
你去了(实际上不需要进行案例测试):
SELECT [user-name],
submissions,
[date],
place,
recency,
DATEDIFF(DAY,
(SELECT TOP(1) [date]
FROM [top-design1] td1
WHERE td1.[user-name] = [top-design1].[user-name]
AND place = 1
AND [date] < [top-design1].[date]
ORDER BY [date] DESC), [date]) as recencywin
FROM [top-design1]
我认为您可以自行管理将其用于插入目的。