2017-11-14 10 views
0

私はクエリにプルする2つのフィールドと、deal_balance(Decimal)とAsOfDate(Date)を持っています。私は2つの異なる方法を試みた。どちらもうまくいきませんでしたが、どちらも近いと思います。唯一の捉え方は、AsOfDateが毎月の最後の就業日であることです。私は整数(1,2、など)、または短縮された月の名前にその変換するかどうかはわかりません(ETC月、2月、。)Tyringは日付フィールドに基づいてピボットする

select Contact_ID, TB_Line, 
    sum(case when [AsOfDate] = 1 then [DEAL_BALANCE] else 0 end) MonthJan, 
    sum(case when [AsOfDate] = 2 then [DEAL_BALANCE] else 0 end) MonthFeb, 
    sum(case when [AsOfDate] = 3 then [DEAL_BALANCE] else 0 end) MonthMar, 
    sum(case when [AsOfDate] = 4 then [DEAL_BALANCE] else 0 end) MonthApr, 
    sum(case when [AsOfDate] = 5 then [DEAL_BALANCE] else 0 end) MonthMay, 
    sum(case when [AsOfDate] = 6 then [DEAL_BALANCE] else 0 end) MonthJun, 
    sum(case when [AsOfDate] = 7 then [DEAL_BALANCE] else 0 end) MonthJul, 
    sum(case when [AsOfDate] = 8 then [DEAL_BALANCE] else 0 end) MonthAug, 
    sum(case when [AsOfDate] = 9 then [DEAL_BALANCE] else 0 end) MonthSep, 
    sum(case when [AsOfDate] = 10 then [DEAL_BALANCE] else 0 end) MonthOct, 
    sum(case when [AsOfDate] = 11 then [DEAL_BALANCE] else 0 end) MonthNov, 
    sum(case when [AsOfDate] = 12 then [DEAL_BALANCE] else 0 end) MonthDec 
from [TBL_HIST] 
group by Contact_ID, TB_Line; 


SELECT * 
FROM 
(
    SELECT Contact_ID, TB_Line, AsOfDate, Deal_Balance 
    FROM [TBL_HIST] 
) src 
pivot 
(
    SUM(DEAL_BALANCE) 
    for AsOfDate in (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec) 
) piv; 

私が使用していますSQL Server 2008の

答えて

1

month()関数を使用してください:

select Contact_ID, TB_Line, 
     sum(case when month([AsOfDate]) = 1 then [DEAL_BALANCE] else 0 end) MonthJan, 
     sum(case when month([AsOfDate]0 = 2 then [DEAL_BALANCE] else 0 end) MonthFeb, 
     . . . 
0

私はちょうど他のバージョンが動作している!!

SELECT * 
FROM 
(
    SELECT Contact_ID, TB_Line, Deal_Balance, DATENAME(Month,[AsOfDate]) AS TheDate 
    FROM [TBL_HIST] 
) AS P 
PIVOT 
(
    SUM(DEAL_BALANCE) for TheDate in (January, February, March, April, May, June, July, August, September, October, November, December) 
) AS PV; 
関連する問題