【问题标题】:Generate multiple rows for single column为单列生成多行
【发布时间】:2022-10-05 02:43:31
【问题描述】:

我的数据如下:

Create table #student(id int, name varchar(20))
create table #test(id int, test_Date datetime, test_type varchar(20))
Insert int #student values (1, 'A')
insert into #student values (2, 'B')
insert into #student values (3, 'C')

insert into #test values (1, '1/1/2022', 'Math')
insert into #test values (1, '1/2/2022', 'Eng')
insert into #test values (1, '1/3/2022', 'Science')

insert into #test values (2, '2/1/2022', 'Math')
insert into #test values (2, '2/2/2022', 'Eng')

insert into #test values (3, '3/1/2022', 'Math')
insert into #test values (3, '3/2/2022', 'Science')

需要以下格式的数据: Output

【问题讨论】:

标签: tsql


【解决方案1】:

看起来您只是想将您的#student 表加入您的#test 表。

    SELECT s.id, s.name, t.test_date. t.test_type 
    FROM #student s
    JOIN #test t
      ON s.id = t.id
   ORDER BY s.id, t.test_date, t.test_type

这将显示每个学生的 ID、姓名、考试日期和考试类型。 按学生编号、考试日期和考试类型排序。

【讨论】:

    【解决方案2】:

    尝试这个

    ;with t0 AS (
    SELECT s.id, s.name, t.test_date, t.test_type
    ,dense_rank() over(partition by s.id order by s.id ,test_date) AS drid
    ,dense_rank() over(partition by s.id,name order by s.id ,test_date) AS drname
    FROM #student s
    JOIN #test t
    ON s.id = t.id
    )
    

    选择 case drid when 1 then id else null end as id ,case drname when 1 then name else null end as name,test_Date,test_type from t0 按 t0.id、t0.name 排序

    【讨论】:

      猜你喜欢
      • 2019-08-09
      • 2018-04-04
      • 2011-10-27
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      相关资源
      最近更新 更多