如何在交叉表中获取多列

How to get multiple columns in Crosstab

我想要来自以下 table 的十字架 table。

十字架 table 应该是这样的

一个pivot table好像不能解决问题,因为一次只能用一列。但在我们的例子中,我们正在处理 4 个不同的列。 (付费、月、年、免费) 我通过将这 4 列拆分为四个不同的枢轴 tables,使用临时 tables 并最终重新组合获得的数据来解决这个问题。但是这个很复杂,又长又乱,总之不是很好看。。。 年份和月份应以升序形式显示,正如您在上面的十字 table 中看到的那样。

我一直在寻找解决方案很长一段时间,但在任何地方都找不到相同的问题。 如果有人能给我一个简短而优雅的解决方案,我将不胜感激。

http://www.sqlfiddle.com/#!18/7216f/2下可以看到问题定义。

谢谢!

您可以使用 row_number() 在子查询中按日期对记录进行排名,然后使用条件聚合进行透视:

select
    ClientId,
    max(case when rn = 1 then Payment end) Payment1,
    max(case when rn = 2 then Payment end) Payment2,
    max(case when rn = 3 then Payment end) Payment3,
    max(case when rn = 1 then [Month] end) Month1,
    max(case when rn = 2 then [Month] end) Month2,
    max(case when rn = 3 then [Month] end) Month3,
    max(case when rn = 1 then [Year] end) Year1,
    max(case when rn = 2 then [Year] end) Year2,
    max(case when rn = 3 then [Year] end) Year3,
    max(case when rn = 1 then FreeOfCharge end) FreeOfCharge1,
    max(case when rn = 2 then FreeOfCharge end) FreeOfCharge2,
    max(case when rn = 3 then FreeOfCharge end) FreeOfCharge3
from (
    select 
        t.*,
        row_number() over(partition by ClientId order by [Year], [Month]) rn
    from mytable t
) t
group by ClientId

您可以加​​入 table 几次,例如:

with p as (
  select
    *, row_number() over(partition by clientid order by year, month) as n
  from Payment
)
select
  p1.clientid,
  p1.payment, p2.payment, p3.payment,
  p1.month, p2.month, p3.month,
  p1.year, p2.year, p3.year,
  p1.freeofcharge, p2.freeofcharge, p3.freeofcharge
from p p1
left join p p2 on p2.clientid = p1.clientid and p2.n = 2
left join p p3 on p3.clientid = p1.clientid and p3.n = 3
where p1.n = 1

Fiddle