【问题标题】:How to create combination groups in sql server如何在sql server中创建组合组
【发布时间】:2021-10-15 20:36:16
【问题描述】:

我有一个给定的表格作为输入:

CategoryPosition CategoryId CategoryName CategoryItemId CategoryItemName CategoryItemPosition
2 10 Gender 11 Male 1
2 10 Gender 12 Female 2
2 10 Gender 13 N/A 3
1 7 Hours 34 0 - 11 1
1 7 Hours 35 12 - 39 2
1 7 Hours 36 40 - 79 3
1 7 Hours 37 80 - 119 4
1 7 Hours 38 120+ 5
0 5 Age 51 16-18 1
0 5 Age 52 19-24 2
0 5 Age 53 25-44 3
0 5 Age 54 45-54 4
0 5 Age 55 55-59 5
0 5 Age 56 60+ 6

总行数:3(来自 Gender 的项目数)+ 5(来自 Hours 的项目数)+ 6(来自 Age 的项目数)= 14

我需要生成一个输出表,它使用来自以下 3 个类别的项目组合组。

GroupPos CategoryPosition CategoryId CategoryName CategoryItemPosition CategoryItemId CategoryItemName
1 0 5 Age 1 51 16-18
1 1 7 Hours 1 34 0 - 11
1 2 10 Gender 1 11 Male
2 0 5 Age 2 52 19-24
2 1 7 Hours 1 34 0 - 11
2 2 10 Gender 1 11 Male
3 0 5 Age 3 53 25-44
3 1 7 Hours 1 34 0 - 11
3 2 10 Gender 1 11 Male

......

总行数:3(Gender 中的项目数)* 5(Hours 中的项目数)* 6(Age 中的项目数)* 3(类别数)= 270

【问题讨论】:

  • 请让这里的好心人知道您到目前为止所做的尝试。就目前而言,您的帖子看起来像家庭作业!由于您已声明这是一个 SQL Server 问题,因此我建议您对可用于细分数据的公用表表达式 (CTE) 进行一些研究。还要查找“交叉连接”。
  • 不要期望得到 270 个结果行。性别、时间和年龄三个类别,所以它是 3 x 5 x 6 = 90 种组合。
  • @ThorstenKettner,OP 还将每个组合取消旋转为 3 行。

标签: sql sql-server


【解决方案1】:

你想要一种交叉连接加反透视

select (row_number() over(order by t1.CategoryItemPosition, t2.CategoryItemPosition, t3.CategoryItemPosition) - 1) / 3 + 1 GroupPos, t.*
from tbl t1 
join tbl t2 on t1.CategoryId = 10 and t2.CategoryId = 7 
join tbl t3 on t3.CategoryId = 5
cross apply (
 values 
   (0, t1.CategoryName, t1.CategoryId, t1.CategoryItemName, t1.CategoryItemId, t1.CategoryItemPosition),
   (1, t2.CategoryName, t2.CategoryId, t2.CategoryItemName, t2.CategoryItemId, t2.CategoryItemPosition),
   (2, t3.CategoryName, t3.CategoryId, t3.CategoryItemName, t3.CategoryItemId, t3.CategoryItemPosition)
) t(CategoryPosition, CategoryName, CategoryId, CategoryItemName, CategoryItemId, CategoryItemPosition)
order by t1.CategoryItemPosition, t2.CategoryItemPosition, t3.CategoryItemPosition

【讨论】:

    【解决方案2】:

    选择不同的属性就像处理不同的表:

    with g as (select categoryitemname as gender from mytable where categoryname = 'Gender')
       , h as (select categoryitemname as hours from mytable where categoryname = 'Hours')
       , a as (select categoryitemname as age from mytable where categoryname = 'Age')
    select *
    from g cross join h cross join a
    order by g.gender, h.hours, a.age;
    

    如果需要,可以向子查询添加更多列。结果看起来与您所期望的结果不同,但我认为这或多或少是您实际追求的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-01
      • 2014-03-07
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多