查询结果需要断行

时间:2017-11-09 08:22:49

标签: sql sql-server tsql sql-server-2014

第二列记录tkt_no中的以下sql代码没有断行,两个tkt_nos之间仍然有一个空格,如AAA111 AAA112,我该如何在两个tkt_nos之间添加一个断行?请帮帮我,谢谢。

SELECT min(post_no) +'~'+ max(post_no) as post_no, min(tkt_no) + char(13)+char(10) + max(tkt_no) as tkt_no,  plic
FROM TEST  
WHERE date = '170711'
GROUP BY plic
ORDER BY post_no

这是上面的sql代码输出:

post_no     | tkt_no      | plic
11001~11010 | AA001 AA010 | N
11011~11099 | AB001 AB089 | N
12000~12001 | BA000 BA001 | C
12002~12099 | BB001 BA098 | C

但我需要在'结果到网格'中查询输出,如下所示:

post_no     | tkt_no      | plic
11001~11010 | AA001       | N
              AA010
11011~11099 | AB001       | N
              AB089  
12000~12001 | BA000       | C
              BA001 
12002~12099 | BB001       | C
              BA098

请帮帮我,谢谢。

1 个答案:

答案 0 :(得分:1)

假设您有以下dataset

post_no     | tkt_no      | plic
11001~11010 | AA001 AA010 | N
11011~11099 | AB001 AB089 | N
12000~12001 | BA000 BA001 | C
12002~12099 | BB001 BA098 | C

&安培;如您所述,您希望以grid样式显示,那么您可以使用xml node方法从中使用网格样式分割数据,如下所示

SELECT 
    case when row_number() over (partition by post_no order by (select 1)) > 1 then '' else post_no end post_no,
    a.value('.', 'VARCHAR(MAX)') [tkt_no],
    case when row_number() over (partition by post_no, plic order by (select 1)) > 1 then '' else plic end plic
    FROM 
(
    SELECT post_no, CAST('<A>'+REPLACE(tkt_no, ' ', '</A><A>')+'</A>' AS XML) AS  tkt_no, plic FROM <your data set>
) A CROSS APPLY tkt_no.nodes ('/A') as split(a)

结果:

post_no     tkt_no  plic
11001~11010 AA001   N
            AA010   
11011~11099 AB001   N
            AB089   
12000~12001 BA000   C
            BA001   
12002~12099 BB001   C
            BA098