将IF行选择为多列

时间:2013-04-03 22:31:40

标签: mysql select if-statement group-by

您好我正在寻求我的查询帮助,该查询当前运行时没有错误但不显示数据,因为我也需要它。我的表存储了电话号码,相关字段是id,phonetype和phonenumber。

运行时,它会按预期返回idHOME PHONEWORK PHONECELL PHONE列,但它仅显示最后一个数字。假设在给定行中有家庭电话和工作电话号码...我只在工作电话列中获取该ID的数据。如果连续有家庭电话,工作电话和手机......我只能在手机电话栏中获取数据。

我需要通过phonetype在唯一列中为给定id的所有phonenumbers排一行。我希望这是有道理的,如果不是查询应该让你知道我在寻找什么...谢谢

SELECT id,
(IF(phonetype = 'HOME PHONE', phonenumbers.phonenumber, '')) AS 'HOME PHONE',
(IF(phonetype = 'WORK PHONE', phonenumbers.phonenumber, '')) AS 'WORK PHONE',
(IF(phonetype = 'CELL PHONE', phonenumbers.phonenumber, '')) AS 'CELL PHONE'
FROM phonenumbers
GROUP BY id;

我正在查询的表格看起来像这样

id | name | phonetype | phonenumber

1  |  Jim  |  HOME PHONE | 0000000001        
1  |  Jim  |  WORK PHONE | 0000000002
2  |  Kim  |  HOME PHONE | 0000000003
2  |  Kim  |  WORK PHONE | 0000000004
2  |  Kim  |  CELL PHONE | 0000000005

我正在寻找的结果看起来像这样......

id | name | home phone | work phone | cell phone

 1 | Jim | 0000000001 | 0000000002 | 
 2 | Kim | 0000000003 | 0000000004 | 0000000005

1 个答案:

答案 0 :(得分:1)

假设每个ID只有一个针对它的电话号码:

SELECT a.id,
(SELECT phonenumbers.phonenumber FROM phonenumbers WHERE phonetype = 'HOME PHONE' AND id = a.id) AS 'HOME PHONE',
(SELECT phonenumbers.phonenumber FROM phonenumbers WHERE phonetype = 'WORK PHONE' AND id = a.id)  AS 'WORK PHONE',
(SELECT phonenumbers.phonenumber FROM phonenumbers WHERE phonetype = 'CELL PHONE' AND id = a.id)  AS 'CELL PHONE'
FROM phonenumbers a
GROUP BY a.id;

可能有帮助。 欢呼声。