1

我有两张表,person(id, phonetype, phonenumber), phonetype(id, txtDisplay)。例如

电话号码

Id  txtDisplay
1   Home Phone
2   Work Phone
3   Mobile Phone

Id  phonetype   phonenumber
0001    1       6310001111
0001    2       6310001112
0002    3       5160002113
0003    2       7180003112

结果表应该是

Id  home_phone  work_phone  mobile_phone
0001    6310001111  6310001112
0002                    5160002113
0003            7180003112

我该如何为此编写查询?

4

2 回答 2

3

仅当您已经知道所有电话类型时,这才有效:

SELECT
  id,
  max(case when phonetype=1 then phonenumber end) as home_phone,
  max(case when phonetype=2 then phonenumber end) as work_phone,
  max(case when phonetype=3 then phonenumber end) as mobile_phone
FROM Person
GROUP BY id
于 2012-11-30T19:11:03.000 回答
2

在 SQL 中,在解析查询时必须知道列名。您不能编写一个根据找到的数据自动扩展列数的查询。

但是,您可以在两个查询中执行此操作:

  1. 首先,从 Phonetype 表中获取所有不同的电话号码类型。

  2. 其次,编写代码以添加与不同电话号码类型一样多的列。

Microsoft SQL Server supports a PIVOT operation that helps for these types of queries a little bit, but you must still know all the distinct values for which you want columns. So my two-step process above applies to Microsoft as well as any other implementation of SQL.

于 2012-11-30T19:12:24.580 回答