2013-12-22 68 views
0

我已回答了我的問題的已回顧版本,但是我發現了一些很好的提示(例如使用rank()over(partition ...) ,似乎並沒有在Sybase版本,我在上班需要將具有相同ID的多個行中的數據轉換爲具有多個列的1行

我希望能運行如下拉動組織數據的過程:

電子郵件|偏好
EMAIL1 | PreferenceXYZ
email1 | PreferenceABC

,呈現在一個表如下所示:

電子郵件|偏好1 | Preference2
email1 | PreferenceXYZ | PreferenceABC

從本質上說,我對同一個人(通過電子郵件記錄最好確定爲唯一標識符)的多條記錄,我想捕捉到這些多喜好給定用戶,併爲每個用戶創建1條個人記錄(每電子郵件)。

回答

1

如果你只有兩個愛好,那麼你可以使用min()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; 
+0

你好 - 偉大的想法。我可以在75%的記錄中使用這種方法,但約25%的記錄有多達7種偏好。所以7是我的上限。 – user3126487

+0

再次感謝 - 不幸的是我收到錯誤(156)關鍵字'over'附近的語法不正確。我曾嘗試過各種各樣的事情。我想知道row_number()是否也不被支持。感謝您的幫助....分析師對於sybase而言相對較新。 – user3126487

+0

您應該用您正在使用的Sybase版本標記您的問題。 –

相關問題