sql - 如何在 tsql 中进行排列(基于集合)

标签 sql sql-server sql-server-2005 t-sql permutation

我有以下输入

PlayerID    MatchPlayed RunsMade
--------    ----------- --------
1           10              200
2           5               100
3           8               24
4           30              50

输出将是

Combined Players    Combined Match Played   Combined runs Made  
----------------    ---------------------   ------------------  
1                   10                      200         
1,2                 15                      300         
1,3                 18                      224
1,4                 40                      250
1,2,3               23                      324
1,2,4               45                      350
1,3,4               48                      274
1,2,3,4             53                      374
2                   5                       100
2,3                 13                      124
2,4                 35                      150
2,3,4               43                      174
3                   8                       24
3,4                 38                      74
4                   30                      50

综合比赛数列是这些球员的比赛数列的值的总和。例如对于组合比赛 1,2,组合比赛值(value)为 10 + 5 = 15。

类似地,Combined Runs Made 是各个球员的 Runs MAde 列的总和。例如对于同一示例,组合运行 MAde 列为 200 +100 =300。

谢谢

最佳答案

设置:

create table Input(PlayerId int, MatchPlayed int, RunsMade int)

insert Input
  select 1, 10, 200
  union all select 2, 5, 100
  union all select 3, 8, 24
  union all select 4, 30, 50

查询:

with cte(Combined, PlayerId, MatchPlayed, RunsMade)
as
(
    select cast(PlayerId as varchar(500)), PlayerId, MatchPlayed, RunsMade
    from Input
    union all
    select cast(cte.Combined + ',' + cast(inp.PlayerId as varchar) as varchar(500)), inp.PlayerId, inp.MatchPlayed + cte.MatchPlayed, inp.RunsMade + cte.RunsMade
    from cte
        join Input inp on
            cte.PlayerId < inp.PlayerId
)
select Combined, MatchPlayed, RunsMade
from cte
order by Combined

关于sql - 如何在 tsql 中进行排列(基于集合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6275187/

相关文章:

sql - 我可以从列 CHECK 约束调用用户定义的函数吗?

sql-server - SSDT 安装程序缺少先决条件 : SQL Server 2016 System CLR Types

c# - 在插入新的数据库行后获得警报。

c# - 将 PictureBox 图像插入到 Sql Server 数据库中

sql-server-2005 - 如何在 SQL Server 中生成字母数字标记?

sql-server - 将日期/时间转换为日期

sql-server-2005 - Sql Server 2005 服务的最低权限集是什么?

php - 如何从 Laravel 返回的数组中获取键的值

SQL Server 触发器更新和增量计数器

sql - EAV vs 序列化对象 vs SQL with Xpath?