Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何为此编写透视图_Sql_Sql Server_Tsql_Pivot - Fatal编程技术网

Sql 如何为此编写透视图

Sql 如何为此编写透视图,sql,sql-server,tsql,pivot,Sql,Sql Server,Tsql,Pivot,我有下表: +---------+-------+ | unit_id | Code | +---------+-------+ | 214825 | D1821 | | 214825 | D0235 | | 214825 | D0710 | +---------+-------+ 我需要执行以下操作的查询: +---------+-------+-------+-------+ | unit_id | code1 | code2 | code3 | +---------+------

我有下表:

+---------+-------+
| unit_id | Code  |
+---------+-------+
|  214825 | D1821 |
|  214825 | D0235 |
|  214825 | D0710 |
+---------+-------+
我需要执行以下操作的查询:

+---------+-------+-------+-------+
| unit_id | code1 | code2 | code3 |
+---------+-------+-------+-------+
|  214825 | D1821 | D0235 | D0710 |
+---------+-------+-------+-------+

我尝试了pivot,但它需要我对数据求和,还有其他方法吗

您可以使用下面的行数来达到您的要求。这样,三个不同列中的代码值将被随机放置(如果在生成行号时未选择排序),或者按照您在我的查询中应用的升序/降序放置-

你可以查一下


如果您使用的是SQL Server 2016或更高版本,这里有一个基于xml和string_agg的替代解决方案:

结果:


是否有其他列值指示代码中的值应放在代码1或代码2或代码3中?没有,但我知道每个单元id有3个值。
SELECT unit_id, 
MAX(CASE WHEN  RN = 1 THEN Code ELSE NULL END) code1,
MAX(CASE WHEN  RN = 2 THEN Code ELSE NULL END) code2,
MAX(CASE WHEN  RN = 3 THEN Code ELSE NULL END) code3
FROM
(
    SELECT *,
    ROW_NUMBER() OVER (PARTITION BY unit_id ORDER BY Code) RN
    -- Here row number will generate for default ascending order over value from column "Code"
    FROM your_table
)A
GROUP BY unit_id
declare @tmp table (unit_id int ,Code varchar(50))

insert into @tmp
values 
  (214825,'d1821')
 ,(214825,'d0235')
 ,(214825,'d0710')

;with splitted
as (
    select unit_id
        ,cast('<x>' + REPLACE(string_agg(Code,'_'), '_', '</x><x>') + '</x>' as xml) as Parts
    from @tmp
    group by unit_id
    )
select unit_id
    ,Parts.value(N'/x[1]', 'varchar(50)') AS code1      
    ,Parts.value(N'/x[2]', 'varchar(50)') AS code2
    ,Parts.value(N'/x[3]', 'varchar(50)') AS code3
from Splitted