1

我查看了已经解决的问题的版本,但是我发现的一些好的技巧(例如使用 rank() over (partition...))似乎不适用于我所在的 Sybase 版本。

我希望运行一个程序来提取按如下方式组织的数据:

电子邮件 | 首选
电子邮件1 | 偏好
XYZ 电子邮件1 | 偏好ABC

并将其呈现在如下表中:

电子邮件 | 偏好1 | 偏好
2 电子邮件 1 | 偏好XYZ | 偏好ABC

本质上,我有同一个人的多个记录(最好通过电子邮件记录识别为唯一标识符),我想为给定用户捕获这些多个偏好并为每个用户(每封电子邮件)创建 1 个单独的记录。

4

1 回答 1

2

如果您只有两个偏好,那么您可以使用min()and max()

select email, min(preference) as preference1,
       (case when min(preference) <> max(preference) then max(preference) end) as preference2
from t
group by email;

编辑:

如果您最多有七个值,则使用以下方式进行旋转row_number()

select email,
       max(case when seqnum = 1 then preference end) as preference1,
       max(case when seqnum = 2 then preference end) as preference2,
       max(case when seqnum = 3 then preference end) as preference3,
       max(case when seqnum = 4 then preference end) as preference4,
       max(case when seqnum = 5 then preference end) as preference5,
       max(case when seqnum = 6 then preference end) as preference6,
       max(case when seqnum = 7 then preference end) as preference7
from (select t.*, row_number() over (partition by email order by preference) as seqnum
      from t
     ) t
group by email;

编辑二:

您实际上可以使用相关子查询而不是row_number()

select email,
       max(case when seqnum = 1 then preference end) as preference1,
       max(case when seqnum = 2 then preference end) as preference2,
       max(case when seqnum = 3 then preference end) as preference3,
       max(case when seqnum = 4 then preference end) as preference4,
       max(case when seqnum = 5 then preference end) as preference5,
       max(case when seqnum = 6 then preference end) as preference6,
       max(case when seqnum = 7 then preference end) as preference7
from (select t.*,
             (select count(*)
              from t t2
              where t2.email = t.email and
                    t2.preference <= t.preference
             ) as seqnum
      from t
     ) t
group by email;
于 2013-12-22T04:04:54.107 回答