我有两个表CX_SOLICITUD_SERVICIO
和CX_SOLICITUD_SALA
,如果NU_CONS_SOSA
有多个CD_CODI_SER_SOSE
,我需要一个添加列的SQL Server查询。
表1:CX_SOLICITUD_SERVICIO
NU_CONS_SOSA_SOSE CD_CODI_SER_SOSE
------------------------------------
777 i684000
777 i705210
777 i595101
778 i684000
778 i549201
756 i132300
763 i132300
758 i132300
761 i132300
761 i132301
表2:CX_SOLICITUD_SALA
NU_CONS_SOSA FE_FECH_SOSA
--------------------------------------------
777 2017-03-01 10:14:00.000
778 2017-03-04 11:14:00.000
756 2017-02-01 12:14:00.000
763 2017-01-15 14:14:00.000
758 2017-02-27 09:14:00.000
761 2017-03-01 10:14:00.000
预期结果:
NU_CONS_SOSA CD_CODI_SER_SOSE_1 CD_CODI_SER_SOSE_2 CD_CODI_SER_SOSE_3
777 i684000 i684000 i595101
778 i684000 i549201 null
756 i132300 null null
763 i132300 null null
758 i132300 null null
761 i132300 i132301 null
我通常会尝试以下查询但不起作用:
SELECT
NU_CONS_SOSA_SOSE, CD_CODI_SER_SOSE
FROM
CX_SOLICITUD_SERVICIO
INNER JOIN
CX_SOLICITUD_SALA ON NU_CONS_SOSA = NU_CONS_SOSA_SOSE
答案 0 :(得分:0)
使用动态sql生成代码pivot()
未知的最大数量CD_CODI_SER_SOSE
:
declare @cols nvarchar(max);
declare @sql nvarchar(max);
select @cols = stuff((
select distinct
',' + quotename('CD_CODI_SER_SOSE_'
+convert(nvarchar(10),row_number() over (
partition by NU_CONS_SOSA_SOSE
order by CD_CODI_SER_SOSE
))
)
from CX_SOLICITUD_SERVICIO
for xml path (''), type).value('.','nvarchar(max)')
,1,1,'');
select @sql = '
select NU_CONS_SOSA_SOSE, ' + @cols + '
from (
select
NU_CONS_SOSA_SOSE
, CD_CODI_SER_SOSE
, rn=''CD_CODI_SER_SOSE_''+convert(nvarchar(10),row_number() over (
partition by NU_CONS_SOSA_SOSE
order by CD_CODI_SER_SOSE
))
from CX_SOLICITUD_SERVICIO
) as a
pivot (max([CD_CODI_SER_SOSE]) for [rn] in (' + @cols + ') ) p';
select @sql as CodeGenerated;
exec sp_executesql @sql;
rextester演示:http://rextester.com/OFWRR74959
代码生成:
select NU_CONS_SOSA_SOSE, [CD_CODI_SER_SOSE_1],[CD_CODI_SER_SOSE_2],[CD_CODI_SER_SOSE_3]
from (
select
NU_CONS_SOSA_SOSE
, CD_CODI_SER_SOSE
, rn='CD_CODI_SER_SOSE_'+convert(nvarchar(10),row_number() over (
partition by NU_CONS_SOSA_SOSE
order by CD_CODI_SER_SOSE
))
from CX_SOLICITUD_SERVICIO
) as a
pivot (max([CD_CODI_SER_SOSE]) for [rn] in ([CD_CODI_SER_SOSE_1],[CD_CODI_SER_SOSE_2],[CD_CODI_SER_SOSE_3]) ) p
结果:
+-------------------+--------------------+--------------------+--------------------+
| NU_CONS_SOSA_SOSE | CD_CODI_SER_SOSE_1 | CD_CODI_SER_SOSE_2 | CD_CODI_SER_SOSE_3 |
+-------------------+--------------------+--------------------+--------------------+
| 756 | i132300 | NULL | NULL |
| 758 | i132300 | NULL | NULL |
| 761 | i132300 | i132301 | NULL |
| 763 | i132300 | NULL | NULL |
| 777 | i595101 | i684000 | i705210 |
| 778 | i549201 | i684000 | NULL |
+-------------------+--------------------+--------------------+--------------------+