Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.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 SERVER中将sql查询返回的值拆分为多列?_Sql_Sql Server - Fatal编程技术网

如何在sql SERVER中将sql查询返回的值拆分为多列?

如何在sql SERVER中将sql查询返回的值拆分为多列?,sql,sql-server,Sql,Sql Server,我有一个函数,在调用时返回以下信息: select * from functionName(null, '1 jan 2016', '30 dec 2016') 输出: pcode PayoutDate 100 2016-02-28 00:00:00:000 100 2016-05-31 00:00:00:000 100 3016-08-31 00:00:00:000 100 301

我有一个函数,在调用时返回以下信息:

select * from functionName(null, '1 jan 2016', '30 dec 2016') 
输出:

    pcode       PayoutDate

   100         2016-02-28 00:00:00:000
   100         2016-05-31 00:00:00:000
   100         3016-08-31 00:00:00:000
   100         3016-11-30 00:00:00:000
   103         2016-02-28 00:00:00:000
   103         2016-05-31 00:00:00:000
   103         3016-08-31 00:00:00:000
   103         3016-11-30 00:00:00:000
我们在2月底、5月底、8月底和11月底向客户付款

因此,我想要实现的是每个月都有自己的日期,如下所示:

pcode    May                        August                November

100    2016-05-31 00:00:00:000  3016-08-31 00:00:00:000  3016-11-30 00:00:00:000 
103    2016-05-31 00:00:00:000  3016-08-31 00:00:00:000  3016-11-30 00:00:00:000 
如何拆分数据集以反映如上所示的情况

我真的不知道如何解决这个问题,任何有想法的人?

使用
PIVOT

SELECT * FROM 
(SELECT pcode, datename(month, PayoutDate) AS Month, PayoutDate FROM yourtable) a
PIVOT
(MIN(PayoutDate) FOR Month IN ([May], [August], [November]))b
输出

pcode May                  August               November
100   2016-05-31T00:00:00Z 3016-08-31T00:00:00Z 3016-11-30T00:00:00Z
103   2016-05-31T00:00:00Z 3016-08-31T00:00:00Z 3016-11-30T00:00:00Z

SQL FIDLE:

可以将函数结果输入到临时表中。 此处示例表名称:SOF_Pcode

select distinct  pcode , (select P1.PayoutDate from SOF_Pcode P1  where  P1.pcode =P.pcode and DATEPART(month,P1.PayoutDate) =5)   As  May 
, (select P1.PayoutDate from SOF_Pcode P1  where  P1.pcode =P.pcode and DATEPART(month,P1.PayoutDate) =8) As August
   , (select P1.PayoutDate from SOF_Pcode P1  where  P1.pcode =P.pcode and DATEPART(month,P1.PayoutDate) =11) As November from SOF_Pcode P