1

我在这里发现了一个类似的问题:Move duplicate values to another column,但我不确定这是否适合我。

以下是数据的设置方式:

Account_ID  Phone Number  Phone Number ID
1           1             1
1           2             2
1           3             3
1           4             4
1           5             5
1           6             6
2           1             1
2           2             2
2           3             3
2           4             4
2           5             5
2           6             6

每个帐户 ID 对 6 个电话号码中的每一个都有一个条目。我希望它看起来像这样:

Account_ID  Phone Number 1  Phone Number 2  Phone Number 3  etc.
1           1               2               3
2           2               2               2

我试过使用这样的CASE语句:

SELECT
Account_ID,
CASE Phone Number ID
WHEN 1 THEN Phone Number END AS "Phone Number 1"
CASE Phone Number ID
WHEN 2 THEN Phone Number END AS "Phone Number 1"
etc.…
GROUP BY 
Case CASE Phone Number ID
WHEN 1 THEN Phone Number END
etc.…

但它仍然没有正确地将数据合并到每个 Account_ID 的单行中。它将与电话号码 ID 对应的电话号码放在正确的列中,但每个 Account_ID 仍然是它自己的行。

有什么想法吗?我上面提供的链接对于这么多领域来说太嵌套、太慢而且太笨重了。我还是写了一个版本来测试它,但它已经运行了 15 分钟。

提前致谢!

4

3 回答 3

2

您可以使用PIVOT来获得所需的输出。


select * from 
(table1 
   pivot (max("Phone Number") for "Phone Number ID"
  in ('1' as "Phone Number 1",
      '2' as "Phone Number 2",
      '3' as "Phone Number 3",
      '4' as "Phone Number 4",
      '5' as "Phone Number 5",
      '6' as "Phone Number 6"))
 )

SQL 小提琴演示

于 2013-03-29T23:27:22.060 回答
0

你很亲密。你需要 acase和 amax和 a group by

select Account_ID,
       max(CASE Phone Number ID = 1 then Phone Number end) as "Phone Number 1",
       max(CASE Phone Number ID = 2 then Phone Number end) as "Phone Number 2",
       max(CASE Phone Number ID = 3 then Phone Number end) as "Phone Number 3",
       . . .
from . . .
group by Account_Id
于 2013-03-29T23:18:31.357 回答
0

你可以用一堆连接来做到这一点

WITH accounts 
     AS (SELECT DISTINCT account_id 
         FROM   phones) 
SELECT a.account_id, 
       one.phone_number   phone_number_1, 
       two.phone_number   phone_number_2, 
       three.phone_number phone_number_3, 
       four.phone_number  phone_number_4, 
       five.phone_number  phone_number_5, 
       six.phone_number   phone_number_6 
FROM   accounts a 
       LEFT JOIN phones one 
              ON a.account_id = one.account_id 
                 AND one.phone_number_id = 1 
       LEFT JOIN phones two 
              ON two.account_id = two.account_id 
                 AND two.phone_number_id = 2 
       LEFT JOIN phones three 
              ON a.account_id = three.account_id 
                 AND three.phone_number_id = 3 
       LEFT JOIN phones four 
              ON a.account_id = four.account_id 
                 AND four.phone_number_id = 4 
       LEFT JOIN phones five 
              ON a.account_id = five.account_id 
                 AND five.phone_number_id = 5 
       LEFT JOIN phones six 
              ON a.account_id = six.account_id 
                 AND six.phone_number_id = 6 

演示

于 2013-03-29T23:22:38.177 回答