我是stackoverflow的新手,我有一个需要你帮助的问题。我有一张类似于下面的表格:
ID, Date, Type
1 1/1/16
1 2/1/16
1 3/1/16 Apple
1 4/1/16
1 5/1/16
1 6/1/16
2 1/1/16 Pear
2 2/1/16
2 3/1/16 Apple
2 4/1/16
2 5/1/16 Banana
2 6/1/16
3 1/1/16
3 2/1/16
3 3/1/16
3 4/1/16
3 5/1/16
3 6/1/16 Pear
我想做的是:
ID, Date, Type
1 1/1/16 Apple
1 2/1/16 Apple
1 3/1/16 Apple
1 4/1/16 Apple
1 5/1/16 Apple
1 6/1/16 Apple
2 1/1/16 Pear
2 2/1/16 Pear
2 3/1/16 Apple
2 4/1/16 Apple
2 5/1/16 Banana
2 6/1/16 Banana
3 1/1/16 Pear
3 2/1/16 Pear
3 3/1/16 Pear
3 4/1/16 Pear
3 5/1/16 Pear
3 6/1/16 Pear
非常感谢任何帮助。提前谢谢大家。
答案 0 :(得分:0)
You can do this Using APPLY
try this query:
SELECT t.id
, t.date
, t.type
, IsNull(t.[type], z.[type]) AS NewType
FROM t
OUTER APPLY
(SELECT x.[type]
FROM t AS x
WHERE x.date =
IsNull(
(SELECT Max(p.date) AS pd FROM t AS p WHERE p.id = t.id AND p.date < t.date AND p.[type] Is Not Null) --Prev Not Null
, (SELECT Min(n.date) AS nd FROM t AS n WHERE n.id = t.id AND n.date > t.date AND n.[type] Is Not Null) --Next Not Null
) AND x.id = t.id
) z