यदि आप order
और item
दोनों के लिए मानों की एक ज्ञात थीं, तो आप मुश्किल क्वेरी में कोड सकता है:
select id,
max(case when `order` = 1 then data end) order1,
max(case when `order` = 2 then data end) order2,
max(case when `order` = 3 then data end) order3,
max(case when item = 1 then price end) item1,
max(case when item = 2 then price end) item2,
max(case when item = 3 then price end) item3,
max(case when item = 4 then price end) item4
from tableA
group by id;
देखें Demo। लेकिन उस समस्या का हिस्सा जो आप करने जा रहे हैं क्योंकि आप डेटा के कई कॉलम को बदलने की कोशिश कर रहे हैं। अंतिम परिणाम प्राप्त करने के लिए मेरा सुझाव पहले डेटा को अप्रचलित करना होगा। MySQL में एक unpivot फ़ंक्शन नहीं है लेकिन आप कॉलम के एकाधिक जोड़े को पंक्तियों में कनवर्ट करने के लिए यूनियन ऑल का उपयोग कर सकते हैं। unpivot करने के लिए कोड निम्न के समान हो जाएगा:
select id, concat('order', `order`) col, data value
from tableA
union all
select id, concat('item', item) col, price value
from tableA;
Demo देखें। इसी का परिणाम हो जाएगा:
| ID | COL | VALUE |
-----------------------
| 1 | order1 | P |
| 1 | order1 | P |
| 1 | order1 | P |
| 1 | item1 | 50 |
| 1 | item2 | 60 |
| 1 | item3 | 70 |
आप देख सकते हैं इस order
/data
और item
/price
की एकाधिक स्तंभों ले लिया है और यह कई पंक्तियों में तब्दील है। एक बार जब कि पूरा हो गया है, तो आप मान वापस स्तंभों में एक मामला साथ एक समग्र समारोह का उपयोग कर परिवर्तित कर सकते हैं:
select id,
max(case when col = 'order1' then value end) order1,
max(case when col = 'order2' then value end) order2,
max(case when col = 'order3' then value end) order3,
max(case when col = 'item1' then value end) item1,
max(case when col = 'item2' then value end) item2,
max(case when col = 'item3' then value end) item3
from
(
select id, concat('order', `order`) col, data value
from tableA
union all
select id, concat('item', item) col, price value
from tableA
) d
group by id;
Demo देखें। अंत में, आप एक गतिशील तैयार बयान क्वेरी में ऊपर कोड बदलने की आवश्यकता:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when col = ''',
col,
''' then value end) as `',
col, '`')
) INTO @sql
FROM
(
select concat('order', `order`) col
from tableA
union all
select concat('item', `item`) col
from tableA
)d;
SET @sql = CONCAT('SELECT id, ', @sql, '
from
(
select id, concat(''order'', `order`) col, data value
from tableA
union all
select id, concat(''item'', item) col, price value
from tableA
) d
group by id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SQL Fiddle with demo देखें। यह परिणाम देता है:
| ID | ORDER1 | ORDER2 | ORDER3 | ITEM1 | ITEM2 | ITEM3 | ITEM4 |
-------------------------------------------------------------------
| 1 | P | Q | (null) | 50 | 60 | 70 | (null) |
| 2 | P | (null) | S | 50 | 60 | (null) | 80 |