我在这里发现了一个类似的问题: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分钟。
提前致谢!
答案 0 :(得分: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 FIDDLE DEMO 强>
答案 1 :(得分:0)
你很亲密。您需要case
和max
以及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
答案 2 :(得分: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