拆分基于逗号的多列并查询以显示多行

时间:2017-06-11 12:01:27

标签: sql-server

我的sql中有一个#table。

从#temp

中选择*
ROWNO| STD     |   SUBJECT   |   STDID
-----+---------+-------------+----------
1    FIFTHGRADE  ENGLISH,BIO     19.23452.52.62464.54
2    SIXTHGRADE  GEO,BIO         19.23452.52.62464.84

我正在使用STRING_SPLIT来分割我的SUBJECT

select STD,value as SUB,STDID
from #temp
cross apply STRING_SPLIT (SUBJECT, ',') 

结果将

enter image description here

但我希望我的结果显示如下

enter image description here

1 代表 STD 值, 2 代表 SUBJECT

我该如何查询?

提前致谢,Jayendran

2 个答案:

答案 0 :(得分:2)

在拆分前使用cross apply (values ...)取消汇总数据:

select 
    stdid
  , s.value
  , case when s.value = t.std then 1 else 2 end as i
from #temp t
  cross apply (values (t.std),(t.subject)) v(value)
  cross apply string_split(v.value, ',') s

dbfiddle.uk演示:http://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=002bc915fe98e1622ac2b401815907a6

返回:

+----------------------+------------+---+
|        stdid         |   value    | i |
+----------------------+------------+---+
| 19.23452.52.62464.54 | FIFTHGRADE | 1 |
| 19.23452.52.62464.54 | ENGLISH    | 2 |
| 19.23452.52.62464.54 | BIO        | 2 |
| 19.23452.52.62464.84 | SIXTHGRADE | 1 |
| 19.23452.52.62464.84 | GEO        | 2 |
| 19.23452.52.62464.84 | BIO        | 2 |
+----------------------+------------+---+

在2016年之前的SQL Server中,使用Jeff Moden的CSV Splitter表值函数:

select 
    stdid
  , s.Item
  , case when s.Item = t.std then 1 else 2 end as i
from temp t
  cross apply (values (t.std),(t.subject)) v(value)
  cross apply delimitedsplit8K(v.value, ',') s

rextester演示:http://rextester.com/MBOMG20846

拆分字符串参考:

答案 1 :(得分:1)

使用union all

select tt.*
from ((select t.STDID, ss.val, 2 as which
       from #temp t cross apply
            string_split(t.subject, ',') ss(val)
      ) union all
      (select t.STDID, t.STD, 1
       from #temp t
      )
     ) tt
order by STDID, which;