当前位置: 代码迷 >> Sql Server >> 请问一个动态生成列名的SQL
  详细解决方案

请问一个动态生成列名的SQL

热度:126   发布时间:2016-04-24 08:50:00.0
请教一个动态生成列名的SQL
本帖最后由 chenpeng0118 于 2015-10-15 10:13:51 编辑
现在的结果如下:

SELECT C.NAME AS '{PRODUCT_NAME}',B.LOT_NAME AS '{LOT_NAME}',
A.PACK_PARENT_NUMBER AS '{CARTON_SN}',
A.CUSTOMER_CARTON_SN AS '{CUSTOMER_CARTON_SN}',
A.PACK_NUMBER AS '{SERIAL_NUMBER_1}'
 FROM DBO.PACK_CARTON A(NOLOCK)
JOIN DBO.QS_LOTS B(NOLOCK)
ON A.LOT_ID=B.LOT_ID
JOIN .DBO.QS_PRODUCTS C(NOLOCK)
ON B.PRODUCT_ID=C.PRODUCT_ID
WHERE A.PACK_PARENT_NUMBER='A110000123777C0001' AND A.PACK_STATUS='0'


结果如下:
{PRODUCT_NAME} {LOT_NAME} {CARTON_SN} {CUSTOMER_CARTON_SN} {SERIAL_NUMBER_1}
A000000000000001 110000123777 A110000123777C0001 999888777 V15080000001
A000000000000001 110000123777 A110000123777C0001 999888777 V15080000002
A000000000000001 110000123777 A110000123777C0001 999888777 V15080000003
A000000000000001 110000123777 A110000123777C0001 999888777 V15080000004
 
如何改为以下的显示结果:列名不是固定的。

{PRODUCT_NAME}   {LOT_NAME}    {CARTON_SN}         {CUSTOMER_CARTON_SN} {SERIAL_NUMBER_1} {SERIAL_NUMBER_2} {SERIAL_NUMBER_3} {SERIAL_NUMBER_4}  
A000000000000001   110000123777  A110000123777C0001   999888777           V15080000001    V15080000002      V15080000003  V15080000004    
------解决思路----------------------
其实就是行列转换  直接在精华帖子里面找吧  
------解决思路----------------------

SELECT C.NAME AS '{PRODUCT_NAME}',B.LOT_NAME AS '{LOT_NAME}',
A.PACK_PARENT_NUMBER AS '{CARTON_SN}',
A.CUSTOMER_CARTON_SN AS '{CUSTOMER_CARTON_SN}',
A.PACK_NUMBER AS '{SERIAL_NUMBER_1}'
into #t
FROM DBO.PACK_CARTON A(NOLOCK)
JOIN DBO.QS_LOTS B(NOLOCK)
ON A.LOT_ID=B.LOT_ID
JOIN .DBO.QS_PRODUCTS C(NOLOCK)
ON B.PRODUCT_ID=C.PRODUCT_ID
WHERE A.PACK_PARENT_NUMBER='A110000123777C0001' AND A.PACK_STATUS='0'


declare @tsql varchar(6000)

select @tsql=isnull(@tsql+',','')
                    +'max(case when [{SERIAL_NUMBER_1}]='''+[{SERIAL_NUMBER_1}]+''' then [{SERIAL_NUMBER_1}] else '''' end) ''SERIAL_NUMBER_'+rn+''' '
 from (select distinct 
                      rtrim(row_number() over(order by [{SERIAL_NUMBER_1}])) 'rn',
                      [{SERIAL_NUMBER_1}] 
           from #t) t

select @tsql='select [{PRODUCT_NAME}],[{LOT_NAME}],[{CARTON_SN}],[{CUSTOMER_CARTON_SN}],'+@tsql
                    +'  from #t '
                    +'  group by [{PRODUCT_NAME}],[{LOT_NAME}],[{CARTON_SN}],[{CUSTOMER_CARTON_SN}] '

exec(@tsql)

/*
{PRODUCT_NAME}       {LOT_NAME}           {CARTON_SN}          {CUSTOMER_CARTON_SN} SERIAL_NUMBER_1      SERIAL_NUMBER_2      SERIAL_NUMBER_3      SERIAL_NUMBER_4
-------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- --------------------
A000000000000001     110000123777         A110000123777C0001   999888777            V15080000001         V15080000002         V15080000003         V15080000004

(1 row(s) affected)
*/
  相关解决方案