×

Loading...
Ad by
  • 技多不压身,工到自然成:安省技工证书特训班,点击咨询报名!
Ad by
  • 技多不压身,工到自然成:安省技工证书特训班,点击咨询报名!

If you need the first Phone Number (order by Phone ID):

Select ID, HomePhone, WorkPhone From(
Select ROW_NUMBER() over(PARTITION by U.ID Order by H.PHONE_ID, W.PHONE_ID) row, U.ID, H.PHONE_NO HomePhone, W.PHONE_NO WorkPhone FROM
[USER] U LEFT JOIN
(Select UP.USER_ID UID, P.PHONE_NO, P.ID PHONE_ID FROM USER_PHONE UP, PHONE P Where UP.PHONE_ID = P.ID AND UP.[TYPE] ='HOME') H
ON U.ID = H.UID LEFT JOIN
(Select UP.USER_ID UID, P.PHONE_NO, P.ID PHONE_ID FROM USER_PHONE UP, PHONE P Where UP.PHONE_ID = P.ID AND UP.[TYPE] ='WORK' ) W
ON U.ID = W.UID
) A Where row =1
Report

Replies, comments and Discussions:

  • 工作学习 / 学科技术讨论 / 请教SQL高手, thanks a lot in advance!
    TABLE USER(
    ID)

    TABLE PHONE(
    ID,
    PHONE_NO)

    TABLE USER_PHONE(
    USER_ID,
    PHONE_ID,
    TYPE (HOME OR WORK OR ELSE))

    I need to get user with home phone and work phone as 1 line. But user can have 0-many home phone or work phone; if multi-phone, get first one; else leave blank.
    How to get a efficient one?
    • you're not clear enough. do you want first home phone +first work phone as the output?
      • yes.
        • if this is for SQL Server 2005 or above, you can directly use pivot table function
          • I am using oracle...
    • 什么数据库?
      SELECT U.USER_ID
      ,H.PHONE_NO
      ,W.PHONE_NO
      FROM (SELECT USER_ID
      ,MIN(CASE WHEN TYPE='HOME' THEN PHONE_ID END) AS HOME_PHONE_ID
      ,MIN(CASE WHEN TYPE='WORK' THEN PHONE_ID END) AS WORK_PHONE_ID
      FROM USER_PHONE
      GROUP BY USER_ID
      ) U
      LEFT JOIN PHONE H ON U.HOME_PHONE_ID = H.ID
      LEFT JOIN PHONE W ON U.WORK_PHONE_ID = W.ID
      • 重写
        SELECT USER_ID
        ,MIN(CASE WHEN TYPE='HOME' THEN P.PHONE_NO END) AS HOME_PHONE_NO
        ,MIN(CASE WHEN TYPE='WORK' THEN P.PHONE_NO END) AS WORK_PHONE_NO
        FROM USER_PHONE U LEFT JOIN PHONE P ON U.PHONE_ID = P.ID
        GROUP BY USER_ID
      • does result return work phone and home phone as 2 rows? I need 1 row for both phone. thanks though
        • it returns one row per user_id with two columns
    • If you need the first Phone Number (order by Phone ID):
      Select ID, HomePhone, WorkPhone From(
      Select ROW_NUMBER() over(PARTITION by U.ID Order by H.PHONE_ID, W.PHONE_ID) row, U.ID, H.PHONE_NO HomePhone, W.PHONE_NO WorkPhone FROM
      [USER] U LEFT JOIN
      (Select UP.USER_ID UID, P.PHONE_NO, P.ID PHONE_ID FROM USER_PHONE UP, PHONE P Where UP.PHONE_ID = P.ID AND UP.[TYPE] ='HOME') H
      ON U.ID = H.UID LEFT JOIN
      (Select UP.USER_ID UID, P.PHONE_NO, P.ID PHONE_ID FROM USER_PHONE UP, PHONE P Where UP.PHONE_ID = P.ID AND UP.[TYPE] ='WORK' ) W
      ON U.ID = W.UID
      ) A Where row =1
    • user defined aggregation function