简体   繁体   English

将多行合并为1

[英]combining multiple rows into 1

I have a table with courses from another school that tie to corresponding courses at our school. 我有一张桌子,上面放着另一所学校的课程,这些课程与我们学校的相应课程联系在一起。 It is a one to many relation ship I'm trying to line it up all on one line based on the transferring school's course for example 这是一对多关系船,例如,我正尝试根据转学学校的课程将其全部排成一行

schoolcode | subj | crsenum  |  oursubj  |  ourcrsenum
------------------------------------------------------
1234       | Art  | 100      |  VisArt   |     200
1234       | Art  | 100      |  VisArt   |     201

outcome I'm trying to get is 我想要得到的结果是

schoolcode | subj | crsnum  | oursubj1   | ourcrsnum1  |  oursubj2 | ourcrsnum2
--------------------------------------------------------------------------------
1234       | Art  | 100     | VisArt     |    200      |  VisArt   |  201

what I've tried still gives me two lines per transfer school course in the table there is also a sequence number corresponding to each course added that is attached to the one incoming course any help would be greatly appreciated! 我尝试过的方法仍然为我在表中的每门转校课程提供了两行内容,还有一个与添加的每门课程相对应的序号,该序号附加到一门即将进入的课程上,对您的帮助将不胜感激! thanks 谢谢

I apologize... I'm working in oracle/sqldeveloper this is information from one table where I'm just trying to select it and flatten it out to one row where the key is the schoolcode|subj|crsenum and then add to that row, all courses that we have associated with that one course. 抱歉...我正在oracle / sqldeveloper中工作,这是一个表中的信息,我只是在这里尝试选择它并将其展平到键为schoolcode | subj | crsenum的一行中,然后添加到该表中行,我们与该课程关联的所有课程。 if there are more than 2, I would like to add it to the same row so for example if for school 1234 subj Art crsenum 100 there is also a course Drawing 200 at our school - I would like it to give me 如果有2个以上,我想将其添加到同一行中,例如,如果对于学校1234主题Art crsenum 100来说,我们学校还有一门课程图200-我想给我

1234     |  Art  | 100 | VisArt  | 200   | VisArt  | 201 | Drawing | 200

I hope that makes sense this is my first question ever 我希望这是我的第一个问题

DECLARE @sql VARCHAR(MAX)
DECLARE @tbl VARCHAR(100)

SET @tbl = 'courses' -- put your table name here

SET @sql = 'SELECT schoolcode, subj, crsenum, ' 

SELECT @sql = @sql + ''''+ oursubj + '''' + ' AS oursubj' + CAST(ROW_NUMBER() OVER (ORDER BY ourcrsenum) AS VARCHAR) + ', ' + CAST(ourcrsenum AS VARCHAR) + ' AS crsenum' + CAST(ROW_NUMBER() OVER (ORDER BY ourcrsenum) AS VARCHAR) + ', '
  FROM courses

SET @sql = LEFT(@sql, LEN(@sql) - 1)

SET @sql = @sql + ' FROM ' + @tbl + ' GROUP BY schoolcode, subj, crsenum'

EXEC(@sql)

Result 结果

schoolcode | subj | crsenum | oursubj1 | crsenum1 | oursubj2 | crsenum2
1234       | Art  | 100     | VisArt   | 200      | VisArt   | 201

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM