我有一个名为“ T”的表
我所需的输出应为
我想选择列'Actual'应当在列'Basic'之间的行,但是如果您以'Model'< / strong> = HT65 'Actual' = 23.2,其范围在'Basic'列的22到24之间,因此我应该在'Level'列的位置获取行是2
应该选择其他行。 您的帮助将不胜感激。
答案 0 :(得分:1)
您可以使用以下解决方案,其中使用多个YYYY-MM-DD
来连接当前行的下一行和最后一行。通过一些其他条件,您可以检查范围:
LEFT JOIN
上面的查询获取所有预期的行。我还添加了一些其他案例,以改进针对这些(特殊)案例的查询。上面的解决方案可以在SQL-Server 2008中使用。
从SQL Server 2012开始,您可以使用LAG
和LEAD
使用以下解决方案:
SELECT t1.Model, t1.Level, t1.Basic, t1.Actual
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Model ORDER BY Basic) AS rn
FROM test
) t1 LEFT JOIN (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Model ORDER BY Basic) AS rn
FROM test
) t2 ON t1.Model = t2.Model AND t1.rn + 1 = t2.rn LEFT JOIN (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Model ORDER BY Basic) AS rn
FROM test
) t3 ON t1.Model = t3.Model AND t1.rn - 1 = t3.rn
WHERE (t1.Actual BETWEEN t3.Basic AND t1.Basic)
OR (t3.Model IS NULL AND t1.Actual < t1.Basic)
OR (t2.Model IS NULL AND t1.Actual > t1.Basic)
ORDER BY t1.Model ASC