SQL Server“分组依据”一个有趣的案例

发布于 2024-08-29 21:34:02 字数 477 浏览 5 评论 0原文

我有一个像这样的表

   ID    ORDER  TEAM   TIME
   IL-1   1   A_Team   11
   IL-1   2   A_Team   3
   IL-1   3   B_Team   2
   IL-1   4   A_Team   1
   IL-1   5   A_Team   1
   IL-2   1   A_Team   5
   IL-2   2   C_Team   3

我想要的是将相同命名的团队分组,这些团队也是连续的团队(根据订单列)

所以结果表应该看起来像

IL-1  1  A_Team 14
IL-1  2  B_Team 2
IL-1  3  A_Team 2
IL-2  1  A_Team 5
IL-2  2  C_Team 3

谢谢

编辑:根据 nang 的答案,我添加了 ID 列到我的桌子上。

I have a table like that

   ID    ORDER  TEAM   TIME
   IL-1   1   A_Team   11
   IL-1   2   A_Team   3
   IL-1   3   B_Team   2
   IL-1   4   A_Team   1
   IL-1   5   A_Team   1
   IL-2   1   A_Team   5
   IL-2   2   C_Team   3

What I want is grouping the same named teams which are also sequential teams (Which is according to the ORDER column)

So the result table should look like

IL-1  1  A_Team 14
IL-1  2  B_Team 2
IL-1  3  A_Team 2
IL-2  1  A_Team 5
IL-2  2  C_Team 3

Thanks

Edit: Depending on the nang's answer, I added the ID column to my table.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

锦欢 2024-09-05 21:34:02

你的例子有问题。为什么第 6 行和第 2 行不应该是“顺序团队”?

1 A_Team 5

2 A_Team 3

但是,也许以下内容对您有用:

select neworder, name, sum([time]) from  (
select min(n1.[order]) neworder, n2.[order], n2.name, n2.[time]
from mytable n1, mytable n2
where n1.Name = n2.Name
and n2.[order] >= n1.[order]
and not exists(select 1 from mytable n3 where n3.name != n1.name and n3.[order] > n1.[order] and n3.[order] < n2.[order])
group by n2.[order], n2.name, n2.[time]) x
group by neworder, name

结果:

新订单名称(无列名称)

1 A_Team 19

4 A_Team 2

3 B_Team 2

2 C_Team 3

There is a problem in your example. Why should rows #6 and #2 not be "sequential teams"?

1 A_Team 5

2 A_Team 3

However, maybe the following is usefull for you:

select neworder, name, sum([time]) from  (
select min(n1.[order]) neworder, n2.[order], n2.name, n2.[time]
from mytable n1, mytable n2
where n1.Name = n2.Name
and n2.[order] >= n1.[order]
and not exists(select 1 from mytable n3 where n3.name != n1.name and n3.[order] > n1.[order] and n3.[order] < n2.[order])
group by n2.[order], n2.name, n2.[time]) x
group by neworder, name

Result:

neworder name (No column name)

1 A_Team 19

4 A_Team 2

3 B_Team 2

2 C_Team 3

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文