这个SQL查询可以吗?
假设我有以下数据:
Employee Task IsCurrent
-------- ---- ---------
Jeff 1 Yes
Jeff 2 No
Jane 1 No
Jane 2 Yes
Jane 3 No
Jane 4 No
Jake 1 Yes
员工有一定数量的任务,其中一项是当前任务。任务编号表示顺序——它们按顺序执行任务,完成最后一个任务后循环回到开头。我想要查询以查看接下来的三个任务。我想要这个结果集:
Employee CurrentTask NextTask NextTask2
-------- ----------- -------- ---------
Jeff 1 2 1
Jane 2 3 4
Jake 1 1 1
这可能吗?我正在使用 SQL 2005
更新:抱歉,我没有明确说明任务编号不一定是连续的——即 Mike 实际上可能有任务 10、23 和 223。所以我不能只是加入寻找下一个连续任务编号。
Suppose I have this data:
Employee Task IsCurrent
-------- ---- ---------
Jeff 1 Yes
Jeff 2 No
Jane 1 No
Jane 2 Yes
Jane 3 No
Jane 4 No
Jake 1 Yes
Employees have some number of tasks, and one of them will be current. The task number indicates an ordering -- they perform tasks in order, looping back to the beginning when they're done with the last one. I'd like a query to see the next three tasks. I'd like this result set:
Employee CurrentTask NextTask NextTask2
-------- ----------- -------- ---------
Jeff 1 2 1
Jane 2 3 4
Jake 1 1 1
Is this possible? I'm using SQL 2005
UPDATE: Sorry, I didn't make clear that the task numbers aren't necessarily sequental -- i.e. Mike might actually have tasks 10, 23, and 223. So I can't just join looking for the next sequential task number.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用:
就像我之前说的,如果 SQL Server 支持 LEAD/LAG 函数会更容易......
Use:
Like I said earlier, would be easier if SQL Server supported LEAD/LAG functions...
如果您只对下一个和之后的下一个感兴趣,您可以使用以下内容:
If you are only interested in the next and the one after that, you can use the following:
使用以下步骤
创建一个包含 Employee、CurrentTask、NextTask 和 NextTask2 列的临时表
插入每个员工及其当前任务的记录。
这是一个简单的 SQL 语句...您可以合并步骤 1 和 2。
然后您需要循环遍历这些记录,使用
TOP 1
和 的组合逐步更新 NextTask 和 NextTask2 列按任务 ASC 排序
Shouldn't be too bad a stored proc with the following steps
Create a temp table with the columns Employee, CurrentTask, NextTask, and NextTask2
Insert records with each employee and their CurrentTask.
This is a simple SQL statement... and you could combine steps 1 and 2.
Then You'll need to loop through these records, progressively updating the NextTask and NextTask2 columns using a combination of
TOP 1
andOrder By Task ASC
也许不是最好的,但你可以尝试这种方式,假设没有超过 2 个 NextTask ;)
PS。也许 PIVOT 可以解决问题,但我不擅长。
Maybe not the best, but you can try this way, asuming there is no more than 2 NextTask's ;)
PS. maybe PIVOT would do the trick, but im not to good at it.
这是一个由两部分组成的问题。首先,您必须解决模数问题(按顺序列出任务,从当前任务开始):
步骤 1:构建一个查询,其结果如下所示(我已根据您的编辑更改了数据)
步骤 2:执行与原始查询进行 UNION
步骤 3:抑制任务# < 的行最低电流或任务#>=最高电流
现在你有了模数数据和一个普通的主元问题。
This is a two-part problem. First, you have to solve the modulus problem (listing tasks in order, starting with the current task):
Step 1: build a query whose results look like this (I've altered the data as per your edit)
Step 2: do a UNION with the original query
Step 3: Suppress rows where task# < lowest current or task# >= highest current
Now you have the modulus data, and an ordinary pivot-problem.