Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL PIVOT: One To Many

I have 2 table in SQL.

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

What i try to achieve is :

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

i try to use pivot on dbo.external statment as

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

The problem is: how can i pivot dbo.external then join the dbo.main in one sql statement?

like image 665
user3165474 Avatar asked Sep 25 '16 05:09

user3165474


2 Answers

Just JOIN the Main table in Pivot source query

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 
  • SQL FIDDLE DEMO
like image 192
Pரதீப் Avatar answered Sep 30 '22 18:09

Pரதீப்


Use WITH clause:

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;
like image 21
Luis Teijon Avatar answered Sep 30 '22 17:09

Luis Teijon