唯一行的SQL语句

时间:2017-12-12 18:44:45

标签: mysql database

我正在尝试从包含帐号,电话号码和电子邮件的表中提取信息。但是,我不确定设计这张桌子的人在想什么。该表设置如下。

AccountID | PhoneType | ******中国

现在您可能会问到电子邮件的存储位置。它们存储在电话号码下。这个数据库的一个例子。

AccountID | PhoneType | PhoneNumber
123456        WORK        111-1111
123456        MOBILE      111-4567
123456        EMAIL     exampleemail@email.com
222222        EMAIL      stupid@table.com

我不知道如何做到这一点,因为我只有SQL的基本知识。我们理想地想要这样的事情:

AccountID | WorkPhone | MobilePhone | Email
123456       111-1111    111-4567     example@email.com
222222                                stupid@table.com

这样做的好方法是什么?我已经尝试了几个IF语句,但没有任何东西让我得到我想要的东西。

3 个答案:

答案 0 :(得分:3)

这样的事情会起作用。如果你有更多的手机类型,这可能会很长:

编辑:根据xQbert的回复,他是对的。您需要在帐户ID上添加一个组,否则您仍将获得多行。

SELECT
    AccountId
    , MAX(CASE WHEN PhoneType = 'WorkPhone' THEN
        PhoneNumber
      ELSE
        NULL
    END) AS 'WorkPhone'
    , MAX(CASE WHEN PhoneType = 'MobilePhone' THEN
        PhoneNumber
      ELSE
        NULL
    END) AS 'MobilePhone'
    , MAX(CASE WHEN PhoneType = 'Email' THEN
        PhoneNumber
      ELSE
        NULL
    END) AS 'Email'
FROM
    MyTable
GROUP BY AccountId

答案 1 :(得分:1)

建立CodeLikeBeaker的响应。

区别不会这样做,因为使用案例旋转时每条记录都是唯一的。但是,通过在每个案例和组中使用max()聚合,我们可以组合记录。

SELECT AccountId
     , max(CASE WHEN PhoneType = 'WorkPhone' THEN PhoneNumber END) AS 'WorkPhone'
     , max(CASE WHEN PhoneType = 'MobilePhone' THEN PhoneNumber END) AS 'MobilePhone'
     , max(CASE WHEN PhoneType = 'Email' THEN PhoneNumber END) AS 'Email'
FROM MyTable
GROUP BY accountID

答案 2 :(得分:-1)

如果手机类型受限于已知设置,则只需加入即可。像这样:

SELECT DISTINCT a.AccountId,
       wp.PhoneNumber as WorkPhone,
       mp.PhoneNumber as MobilePhone,
       em.PhoneNumber as Email
    FROM MyTable As a
    LEFT JOIN (SELECT AccountId, PhoneNumber FROM MyTable
               WHERE PhoneType = 'WORK') As wp
         ON a.AccountId = wp.AccountId
    LEFT JOIN (SELECT AccountId, PhoneNumber FROM MyTable
               WHERE PhoneType = 'MOBILE') As mp
         ON a.AccountId = mp.AccountId
    LEFT JOIN (SELECT AccountId, PhoneNumber FROM MyTable
               WHERE PhoneType = 'EMAIL') As em
         ON a.AccountId = em.AccountId