在SQL Server中选择多行到列

时间:2017-07-28 13:02:46

标签: sql sql-server database sql-server-2008

我希望通过SQL服务器输出以下内容。

表A

| Id   |   Name   | 2016 | 2017 |  
 - - - - - - - - -  - - - - - - - 
| 1    |  ABCDEFG |      |      |
| 2    |  XYZLMON |      |      |

表B

| Id   | Value | Year |  
 - - - - - - - - - - -
| 1    |  F    | 2016 |
| 1    |  G    | 2017 |

输出

| Id   |   Name   | 2016 | 2017 |  
 - - - - - - - - -  - - - - - - - 
| 1    |  ABCDEFG |  F   |  G   |
| 2    |  XYZLMON |      |      |

3 个答案:

答案 0 :(得分:1)

您可以使用两个连接执行此操作:

select a.*, b2016.value as val2016, b2017.value as val2017
from a left join
     b b2016
     on a.id = b.id and b.year = 2016 left join
     b b2017
     on a.id = b.id and b.year = 2017;

答案 1 :(得分:1)

您可以按以下方式加入这些表格并进行转播:

Select * 
from (
    Select 
        a.Id, 
        a.[Name], 
        b.[Value], 
        b.[year] 
    from tablea a
    left join tableb b on a.Id = b.id
) a
pivot (
    max([Value]) 
    for [Year] in ([2016],[2017]) 
) p

答案 2 :(得分:0)

试试这个:

SELECT 
    tbla.id as Id, 
    tbla.name as Name, 
    (SELECT 
        value 
     FROM tblb 
     WHERE tblb.Id = tbla.id 
     AND tblb.Year ='2016') as 2016, 
     (SELECT 
          value 
      FROM tblb 
      WHERE tblb.Id = tbla.id 
      AND tblb.Year ='2017') as 2017 
FROM tbla;