根据日期字段进行旋转

时间:2017-11-14 22:15:06

标签: sql sql-server

我有2个字段要插入查询,加上deal_balance(Decimal)和AsOfDate(Date)。我尝试了两种不同的方式;既没有奏效,但我认为两者都很接近。唯一的问题是AsOfDate是每个月的最后一个工作日。我不确定如何将其转换为整数(1,2等)或缩写月份的名称(Jan,Feb等)

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。

2 个答案:

答案 0 :(得分: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,
       . . .

答案 1 :(得分: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;