我一直在阅读如何解决这个问题,但由于我缺乏正确构建此查询或甚至搜索正确答案的知识,我将不得不在这里询问并希望您可以帮助我。
假设我有一个名为VENDORS
的表格如下:
ID|name |phone |phone_type
1| Andy |305332 |office
1| Andy |999999 |fax
1| Andy |555555 |cellphone
2| Jack |222222 |office
2| Jack |444444 |fax
3| Peter |234234 |office
3| Peter |434345 |cellphone
如何构建查询以便我得到:
ID|name |phone |fax |cellphone
1| Andy |305332 |999999 |555555
2| Jack |222222 |444444 |NULL
3| Peter |234234 |NULL |434345
我在想这样的事情:
SELECT
id,
name,
CASE
WHEN phone_type = 'office'
THEN phone END AS phone
WHEN phone_type = 'fax'
THEN phone END AS fax,
WHEN phone_type = 'cellphone'
THEN phone END AS cellphone
FROM `VENDORS`
GROUP BY id
但当然这不起作用,不知道如何得到我想要的东西,这似乎很容易,但我完全迷失了。
答案 0 :(得分:1)
尝试
SELECT
id,
name,
CASE WHEN phone_type = 'office'
THEN phone
ELSE NULL END AS office,
CASE WHEN phone_type = 'fax'
THEN phone
ELSE NULL END AS fax,
CASE WHEN phone_type = 'cellphone'
THEN phone
ELSE NULL END AS cellphone
FROM `VENDORS`
GROUP BY name
答案 1 :(得分:1)
这是一个带子查询的工作解决方案:
SELECT id, name,
(SELECT phone FROM vendors WHERE id = v.id AND phone_type = 'office') as office,
(SELECT phone FROM vendors WHERE id = v.id AND phone_type = 'fax') as fax,
(SELECT phone FROM vendors WHERE id = v.id AND phone_type = 'cellphone') as cellphone
FROM vendors v
GROUP BY id
你可以在这里找到一个工作小提琴: http://sqlfiddle.com/#!9/42b355/2