列中的列值

时间:2011-11-30 08:40:14

标签: sql-server-2008

主要表

Id name 

1 xxxxx
2 yyyyy
3 zzzzzz

外国表

Id   phonetype        phoneno 

1    home             111111
1    work             222222
1    mob              333333
2    work             444444
2    mob              555555

我需要显示

Name    workphone   homephone        mob

xxxxx   222222       111111        333333
yyyyy   444444        null         555555

如何在sql server 2008中编写查询

3 个答案:

答案 0 :(得分:2)

尝试这样的事情:

SELECT 
    pt.NAME,
    (SELECT PhoneNo FROM dbo.Secondary s WHERE s.ID = pt.ID AND s.PhoneType = 'home') 'Home',
    (SELECT PhoneNo FROM dbo.Secondary s WHERE s.ID = pt.ID AND s.PhoneType = 'work') 'Work',
    (SELECT PhoneNo FROM dbo.Secondary s WHERE s.ID = pt.ID AND s.PhoneType = 'mob') 'Mobile'
FROM dbo.PrimaryTable pt

答案 1 :(得分:2)

以下是另外两种方法,只是为了完整性:

  1. SELECT
      p.name,
      MAX(CASE t.phonetype WHEN 'work' THEN t.phoneno END) AS workphone,
      MAX(CASE t.phonetype WHEN 'home' THEN t.phoneno END) AS homephone,
      MAX(CASE t.phonetype WHEN 'mob' THEN t.phoneno END) AS mobilephone
    FROM people p
      INNER JOIN phones t ON p.Id = t.Id
    GROUP BY p.Id, p.Name
    
  2. SELECT
      p.name,
      w.phoneno AS workphone,
      h.phoneno AS homephone,
      m.phoneno AS mobilephone
    FROM people p
      LEFT JOIN phones w ON p.Id = w.Id AND w.phonetype = 'work'
      LEFT JOIN phones h ON p.Id = h.Id AND h.phonetype = 'home'
      LEFT JOIN phones m ON p.Id = m.Id AND m.phonetype = 'mob'
    

答案 2 :(得分:1)

除了Marc_s解决方案,您还可以使用PIVOT来实现这一目标:

SELECT [Name], [home], [work], [mob]
FROM
(
    SELECT [Name], phonetype, phoneno
    FROM Customer c join ContactDetail cd on c.Id = cd.id
) t
PIVOT
(
    MIN(PhoneNo) FOR [phonetype] IN ([home], [work], [mob]) 
) AS pvt
ORDER BY pvt.[Name]