我想在SQL Server中执行数据透视,但是有一定条件

时间:2019-07-15 19:05:22

标签: sql sql-server pivot

我有一个这样的桌子

ID    |Date Purchase    |Payment Amount    |Payment Date
------|-----------------|------------------|-----------------
1550  |December 2018    |$120              |January, 5 2019
1550  |December 2018    |$120              |February, 7 2019
1551  |December 2018    |$130              |January , 4 2019
1551  |December 2018    |$135              |February 9, 2019
1551  |December 2018    |$90               |April 10, 2019
1552  |November 2018    |$102              |January, 5 2019
1552  |November 2018    |$900              |March 7, 2019

我正在尝试获得这样的输出:

ID    |Month 0    |Month 1    |Month 2    |Month 3    |Month 4   |Month 5
------|-----------|-----------|-----------|-----------|----------|--------
1550  |0          |$120       |$120       |0          |0         |0
1551  |0          |$130       |$135       |0          |$90       |0
1552  |0          |0          |$102       |0          |$900      |0 

即这些月份应该是从购买之日算起,我要根据“付款日期”来枢转“付款金额”列,并且要将“购买日期”从“购买日期”转换为“月份0”到“月份n”。

我尝试了简单的数据透视功能,但无法更改月份格式

1 个答案:

答案 0 :(得分:1)

假设您不需要动态SQL

唯一的技巧是将字符串转换为日期,然后计算datediff(MONTH,...)

示例dbFiddle

Select ID
      ,[Month 1] = IsNull([1],0)
      ,[Month 2] = IsNull([2],0)
      ,[Month 3] = IsNull([3],0)
      ,[Month 4] = IsNull([4],0)
      ,[Month 5] = IsNull([5],0)
 From  (
            Select ID
                  ,Item = DateDiff(MONTH,try_convert(date,replace([Date Purchase],' ',' 1, ')),try_convert(date,replace([Payment Date],',',' ')))
                  ,Value =[Payment Amount]
            From YourTable
       ) src
 Pivot ( sum(Value) for Item in ([1],[2],[3],[4],[5]) ) pvt

返回

ID      Month 0  Month 1    Month 2  Month 3    Month 4  Month 5
1550    0.00     120.00     120.00   0.00       0.00     0.00
1551    0.00     130.00     135.00   0.00       90.00    0.00
1552    0.00     0.00       102.00   0.00       900.00   0.00