多个逗号分隔的字符串列到多行

时间:2017-01-25 16:26:57

标签: sql-server sql-server-2008-r2

我有一个场景,我在#Testdata临时表中有如下数据。

create table #Testdata(SomeID int, OtherID int, Data varchar(max), Data2 VARCHAR(MAX))
insert #Testdata select 1, 9, '18,20,22', '12,13'
insert #Testdata select 2, 8, '17,19', ''
insert #Testdata select 3, 7, '13,19,20', '14,,50'
insert #Testdata select 4, 6, '', ''

现在我需要显示如下结果。

|SomeId|OtherID|Data|Data2|
|1     |9      |18  |12   |
|1     |9      |20  |13   |
|1     |9      |22  |     |
|2     |8      |17  |     |
|2     |8      |19  |     |
|3     |7      |13  |14   |
|3     |7      |19  |     |
|3     |7      |10  |50   |
|4     |6      |    |     |

非常感谢任何回复。

由于

2 个答案:

答案 0 :(得分:2)

例如,您可以安装Jeff Moden的DelimitedSplit8k。结果集将包含项目和项目编号,因此使用项目编号,您可以加入分割在一起的2个字符串。

答案 1 :(得分:2)

使用Jeff Moden's string split function,您可以执行以下操作以获得所需的输出,但我确信有更有效的方法...

import pymongo


conn = pymongo.MongoClient('mongodb://localhost')

def remove_lowest_hw():
    db = conn.school
    students = db.students

    # first sort scores in ascending order
    students.update_many({}, {'$push':{'scores':{'$each':[], '$sort':{'score': 1}}}})

    # then collect the lowest homework score for each student via projection
    cursor = students.find({}, {'scores':{'$elemMatch':{'type':'homework'}}})

    # iterate over each student, trimming each of the lowest homework score
    for stu in cursor:
        students.update({'_id':stu['_id']}, {'$pull':{'scores':{'score':stu['scores'][0]['score']}}})

remove_lowest_hw()

conn.close()