SQL PIVOT:一对多

时间:2016-09-25 05:04:07

标签: sql sql-server pivot

我在SQL中有2个表。

dbo.main

|id | mid | tid 
 1    yes    no

dbo.external

| id | type | element |
  1    c        9
  1    d        10
  1    h        11
  1    g        12

我努力实现的目标是:

| id | mid | tid | c | d | h | g  |
  1    yes    no   9  10  11   12

我尝试在dbo.external statment上使用pivot作为

SELECT *
FROM 
(
  SELECT id,type,element
  FROM dbo.external
) SRC
PIVOT
(
  MAX(FIELD_DATA)
  FOR FIELD_NUMBER IN (id,type,element)
) PIV;

问题是:  我怎么能转动dbo.external然后在一个sql语句中加入dbo.main?

2 个答案:

答案 0 :(得分:5)

JOIN源查询

中的Main表格Pivot
SELECT * 
FROM   (SELECT e.id,mid,tid,[element],[type] 
        FROM   dbo.[external] e 
               JOIN main m 
                 ON e.id = m.id) a 
       PIVOT ( Max([element]) 
             FOR [type] IN ([c],[d],[h],[g]) ) PIV 

答案 1 :(得分:4)

使用WITH子句:

WITH temp AS(
   -- here make the join
)
SELECT id,mid,tid, c,d,h,g
FROM temp
PIVOT
(
  MAX(FIELD_DATA)
  FOR type IN (c,d,h,g)
) as PIV;