如何仅透视选择的行数

时间:2019-02-22 12:20:29

标签: sql pivot

我是SQL新手,有一个问题。我有以下数据:

Name            Description     Format

John            An Old Man      M
Mary            An Old Woman    F
Smith           A Boy           M
Doe             A Girl          F
Carry           Sister          F
Kevin           Brother         M
Joe             Cousin          M
Anne            Cousin          F

我需要它如下所示。有可能吗?

Name1   Description1 Format1 Name2 Description2 Format2 Name3 Description3 Format3

John    An Old Man    M      Mary  An Old Woman  F      Smith  A Boy       M 
Doe     A Girl        F      Carry Sister        F      Kevin  Brother     M 
Joe     Cousin        M      Anne  Cousin        F

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合。但是窍门是一些算法,可以将名称分成三组:

select max(case when seqnum % 3 = 0 then name end) as name_1,
       max(case when seqnum % 3 = 0 then description end) as description_1,
       max(case when seqnum % 3 = 0 then format end) as format_1,
       max(case when seqnum % 3 = 1 then name end) as name_12
       max(case when seqnum % 3 = 1 then description end) as description_2,
       max(case when seqnum % 3 = 1 then format end) as format_2,
       max(case when seqnum % 3 = 2 then name end) as name_3,
       max(case when seqnum % 3 = 2 then description end) as description_3,
       max(case when seqnum % 3 = 2 then format end) as format_3
from (select t.*,
             (row_number() over (order by name) - 1) as seqnum
      from t
     ) t
group by seqnum / 3;