简体   繁体   English

SQL 服务器透视 - 无中间列,无聚合

[英]SQL Server Pivoting - No middle column, no aggregation

--EDIT: original table sample, requested in comments --编辑:原始表格示例,在评论中要求

job_id job_id change_id change_id change改变
1 1 1 1 5□6□ 5□6□
1 1 2 2 7□8□ 7□8□
1 1 3 3 9□10□ 9□10□
2 2 4 4 1□3□ 1□3□

This is a C# reflection of an object to serialise the data in the Change field.这是 object 的 C# 反射,用于序列化 Change 字段中的数据。

The desired result is the following:期望的结果如下:

Job ID作业编号 Change ID更改 ID Change from从改变 Change to改成
1 1 1 1 5 5 6 6
1 1 2 2 7 7 8 8
1 1 3 3 9 9 10 10
2 2 4 4 1 1 3 3

I managed to identify the character as CHAR(1), in order to be able to split it using the following query (which lead to the unpivoted table, which might or might not be useful- apparently not as per comments below, since the order is uncertain):我设法将字符标识为 CHAR(1),以便能够使用以下查询将其拆分(这会导致未透视表,这可能有用也可能没有用 - 显然不是按照下面的评论,因为订单不确定):

SELECT job_id, change_id, VALUE change 
FROM change_table
CROSS APPLY STRING_SPLIT(change,CHAR(1))
Job ID作业编号 Change ID更改 ID Changes变化
1 1 1 1 5 5
1 1 1 1 6 6
1 1 1 1
1 1 2 2 7 7
1 1 2 2 8 8
1 1 2 2
1 1 3 3 9 9
1 1 3 3 10 10
1 1 3 3
2 2 4 4 1 1
2 2 4 4 3 3
2 2 4 4

Assuming, the Changes value of the last of three rows is '' .假设三行中最后一行的Changes值为''

Does this work for you?这对你有用吗?

SELECT 
    *,
    '' blank
FROM (    
    SELECT 
        job_id,
        change_id,
        changes AS changes_from,
        LEAD(changes) OVER (PARTITION BY job_id, change_id ORDER BY job_id) AS changes_to
   FROM jobs
) j
WHERE changes_from != '' AND changes_to != ''

Output Output

job_id job_id change_id change_id changes_from changes_from changes_to changes_to blank空白的
1 1 1 1 5 5 6 6
1 1 1 1 7 7 8 8
1 1 2 2 9 9 10 10
2 2 3 3 1 1 3 3

db<>fiddle here db<> 在这里摆弄

It's kind of painful when delimited data has a trailing delimiter.当分隔数据有一个尾随分隔符时,这有点痛苦。 Here is a simple solution to this using PARSENAME.这是一个使用 PARSENAME 的简单解决方案。 I had to add and extra space back on the end here because the PARSENAME function gets confused when the last character is a period.我不得不在最后添加额外的空间,因为当最后一个字符是句点时,PARSENAME function 会混淆。

declare @Changes table
(
    job_id int
    , change_id int
    , change varchar(20)
)

insert @Changes values
(1, 1, '5 6 ')
, (1, 2, '7 8 ')
, (1, 3, '9 10 ')
, (2, 4, '1 3 ')

select c.job_id
    , c.change_id
    , ChangeFrom = parsename(replace(c.change, ' ', '.') + ' ', 3)
    , ChangeTo = parsename(replace(c.change, ' ', '.') + ' ', 2)
from @Changes c

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

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