2017-07-27 4 views
1

は、私が呼ばれたときに、以下の情報を返す関数を持っている: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   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 

私は上記のように反映するように設定データを分割できますか?

私は実際にどのようにこれに取り組むことができるのか分かりません。

答えて

2

使用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フィドル:http://sqlfiddle.com/#!6/9ed49/11/0

+0

ありがとうございました – Immortal

1

が一時テーブルに関数の結果を入力することができます。 ここに例のテーブル名: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 
関連する問題