首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在sql SERVER中将SQL查询返回的值拆分为多个列?

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

Stack Overflow用户
提问于 2017-07-27 17:12:27
回答 2查看 53关注 0票数 1

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

代码语言:javascript
复制
select * from functionName(null, '1 jan 2016', '30 dec 2016') 

输出:

代码语言:javascript
复制
    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月底向客户支付款项。

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

代码语言:javascript
复制
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 

如何拆分数据集以进行如上所示的反映?

我真的不知道如何解决这个问题,有谁有什么想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-07-27 17:23:36

使用PIVOT

代码语言:javascript
复制
SELECT * FROM 
(SELECT pcode, datename(month, PayoutDate) AS Month, PayoutDate FROM yourtable) a
PIVOT
(MIN(PayoutDate) FOR Month IN ([May], [August], [November]))b

输出

代码语言:javascript
复制
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 Fiddle:http://sqlfiddle.com/#!6/9ed49/11/0

票数 2
EN

Stack Overflow用户

发布于 2017-07-27 18:13:54

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

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45346294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档