Как повернуть только выбранное количество строк - PullRequest
0 голосов
/ 22 февраля 2019

Я новичок в 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 голосов
/ 22 февраля 2019

Вы можете использовать условное агрегирование.Но уловка заключается в некоторой арифметике, чтобы получить имена в группах по три:

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;
...