Converting column into row using "|" as separators - mysql

Please take a look at this Fiddle Example
I want to convert each field into a row from this table:
CREATE TABLE product
(`ID` int, `name` varchar(1), `category` varchar(11), `price` int,`year`int)
;
INSERT INTO product
(`ID`, `name`, `category`, `price`,`year`)
VALUES
(1, 'A', 'Outdoor', 25,2010),
(2, 'A', 'Doll', 34,2009),
(3, 'C', 'Doll', 25,2008),
(4, 'D', 'Outdoor', 20,2010),
(5, 'E', 'Brainteaser', 22,2010),
(6, 'E', 'Brainteaser', 22,2009),
(7, 'G', 'Brainteaser', 30,2009),
(8, 'G', 'Brainteaser', 30,2009)
;
Here's the output I'm trying to get:
field value
name A,C,D,E,G
category Brainteaser,Doll,Outdoor
price 20,22,25,30,34
year 2008,2009,2010
I read a thread about pivoting table with UNION and MAX but I was lost at using MAX with GROUP_CONCAT
SELECT
MAX(CASE WHEN ... GROUP_CONCAT(DISTINCT (value) SEPARATOR '|')) as value
from(
select id,name value, 'name' field
from product
union all
select id,category value, 'category' field
from product
union all
select id,price value, 'price' field
from product
union all
select id,year value, 'year' field
from product
)
GROUP BY field
order by value
Can anyone show me how to get that output?

This will give you expected output:
SELECT 'name' AS `field`. GROUP_CONCAT(DISTINCT `name` ORDER BY `name`) AS `value`
FROM product
UNION ALL
SELECT 'category' AS `field`. GROUP_CONCAT(DISTINCT `category` ORDER BY `category`) AS `value`
FROM product
UNION ALL
SELECT 'price' AS `field`. GROUP_CONCAT(DISTINCT `price` ORDER BY `price`) AS `value`
FROM product
UNION ALL
SELECT 'year' AS `field`. GROUP_CONCAT(DISTINCT `year` ORDER BY `year`) AS `value`
FROM product
Added ORDER BY because looks like you need sorted output

something like this?? Using union all for better proformance and incase there are any dupilcates.
SELECT 'name' field, group_concat(DISTINCT name ORDER BY name SEPARATOR '|') value FROM product
UNION ALL
SELECT 'category' field, group_concat(DISTINCT category ORDER BY category SEPARATOR '|') value FROM product
UNION ALL
SELECT 'price' field, group_concat(DISTINCT price ORDER BY price SEPARATOR '|') value FROM product
UNION ALL
SELECT 'year' field, group_concat(DISTINCT year ORDER BY year SEPARATOR '|') value FROM product;
EDIT:
If you would like to do this with just one query you can achieve it this way.
SELECT
#uName := group_concat(DISTINCT name ORDER BY name SEPARATOR '|'),
#uCat := group_concat(DISTINCT category ORDER BY category SEPARATOR '|') uCat,
#uPrice := group_concat(DISTINCT price ORDER BY price SEPARATOR '|') uPrice,
#uYear := group_concat(DISTINCT year ORDER BY year SEPARATOR '|') uYear
FROM product;
SELECT 'name' field, #uName value
UNION ALL
SELECT 'category' field, #uCat value
UNION ALL
SELECT 'price' field, #uPrice value
UNION ALL
SELECT 'year' field, #uYear value;
NOTE: you can do ORDER BY inside the GROUP_CONCAT

There is a way to complete your request without having to query your table with many queries. In fact, method below is a way to turn any table to pivot. It will use mysql prepared statements for prepare SQL and later execute it:
SELECT
GROUP_CONCAT(f SEPARATOR ' UNION ALL ')
FROM
(SELECT
CONCAT(
'SELECT "',
column_name,
'" AS `field`, GROUP_CONCAT(DISTINCT ',
column_name,
') AS `value` FROM `',
#table_name,
'`'
) AS f
FROM
((SELECT
column_name
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
table_name=#table_name &&
table_schema=#schema_name
) AS fields
CROSS JOIN
(SELECT
#table_name := 'product',
#schema_name:= 'test'
) AS init)
) AS sqldata
The sql above will result in a string, which can be used to assign a variable, like
mysql> SET #sql:=(SELECT GROUP_CONCAT(f SEPARATOR ' UNION ALL ') FROM (SELECT CONCAT('SELECT "', column_name,'" AS `field`, GROUP_CONCAT(DISTINCT ', column_name,') AS `value` FROM `', #table_name, '`') AS f FROM ((SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name=#table_name && table_schema=#schema_name) AS fields CROSS JOIN (SELECT #table_name:='product', #schema_name:='test') AS init)) AS sqldata);
Query OK, 0 rows affected (0.03 sec)
next, prepare:
mysql> PREPARE stmt FROM #sql;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
finally, execute it:
mysql> EXECUTE stmt;
+----------+--------------------------+
| field | value |
+----------+--------------------------+
| ID | 1,2,3,4,5,6,7,8 |
| name | A,C,D,E,G |
| category | Outdoor,Doll,Brainteaser |
| price | 25,34,20,22,30 |
| year | 2010,2009,2008 |
+----------+--------------------------+
5 rows in set (0.00 sec)
The benefit is that you are independent from table structure, field names, e tc. It's a general way - so you may use it to create such pivots for any table.
Few words about variables #table_name and #schema_name. They specify which table and in which schema would be pivoted. In sample above, I used CROSS JOIN to set them in-place, but you may set them separately, to maintain different tables for pivots.

Related

Join into pivot (?)

I wonder how to replace such a table
(the table is the result of 3x LEFT JOIN)
SELECT *
FROM users
LEFT JOIN items on users.id = items.id
LEFT JOIN items_additional on users.id = items_additional.items_id
LEFT JOIN items_ask_user on users.id = items_ask_user.items_id';
ID
item_id
name
surname
addition
question
amount
1
1
Gladys
Warner
hot-dog
mayo
14
2
1
Gladys
Warner
pizza
chilli
11
3
2
Harrison
Croft
pizza
4
2
Harrison
Croft
burger
chilli
11
5
2
Harrison
Croft
hod-dog
mayo
14
to somthing like
ID
item_id
name
surname
addition
addition2
addition3
question1
question2
question3
amount
1
1
Gladys
Warner
hot-dog
pizza
-
mayo
chilli
-
25
2
2
Harrison
Croft
pizza
burger
hod-dog
chilli
mayo
-
25
the number of additions or questions may increase or decrease, depending on person.
Edit
SET #sql = NULL;
WITH cte AS(
SELECT DISTINCT ROW_NUMBER() OVER(PARTITION BY user_id) AS idx
FROM users
LEFT JOIN items on users.id = items.id
LEFT JOIN items_additional on users.id = items_additional.items_id
LEFT JOIN items_ask_user on users.id = items_ask_user.items_id
)
SELECT GROUP_CONCAT(
CONCAT('MAX(IF(rn_add = ', cte.idx, ', additional_option_name, NULL)) AS additional_option_name', cte.idx, ','
'MAX(IF(rn_qst = ', cte.idx, ', ask_user, NULL)) AS ask_user', cte.idx
)) INTO #sql
FROM cte;
SET #cte = 'WITH cte AS(SELECT *, ROW_NUMBER() OVER(PARTITION BY name, surname ORDER BY IF(additional_option_name IS NULL, 1, 0), `event_items`.`id`) AS rn_add, ROW_NUMBER() OVER(PARTITION BY name, surname ORDER BY IF(ask_user IS NULL, 1, 0), `event_items`.`id`) AS rn_qst
FROM users
LEFT JOIN event_items on users.id = event_items.id
LEFT JOIN event_items_additional on users.id = event_items_additional.items_id
LEFT JOIN event_items_ask_user on users.id = event_items_ask_user.items_id';
SET #sql = CONCAT(#cte,
'SELECT `event_items`.`id`, user_id, name, surname,',
#sql,
',SUM(additional_option_price) AS additional_option_price FROM cte GROUP BY user_id, name, surname'
);
SELECT #sql;
PREPARE stmt1 FROM #sql;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
Edit2
Schema demo here
Will just throw this here as a possibility - it won't give you dynamic columns but may be of use depending on how you intend to consume the data.
It's certaintly less faff and more performant if you can.
select
item_Id, name, surname,
group_concat(addition separator ', ') Additions,
group_concat(question separator ', ') Questions,
Sum(amount) amount
from t
group by item_Id, name, surname;
As long as the dynamic solution is based on the static one, for reasons of clarity I'll first explain the static one by assuming that, as in the example your provided, there are exactly 3 fields at max, for addition and question fields.
Let's look at the static solution first, by assuming that we have specifically 3 fields. In this case what you can do is compute a row number for each addition and question, which will be used to match the specific value at the required index for each of the three fields addition1, addition2 and addition3 (same goes for question), using an IF statement. In order to remove the NULL values that are generated by this statement, we can select the maximum value and aggregate over item_id, name and surname
WITH cte AS(
SELECT *,
ROW_NUMBER() OVER(
PARTITION BY name, surname
ORDER BY IF(addition IS NULL, 1, 0),
ID ) AS rn_add,
ROW_NUMBER() OVER(
PARTITION BY name, surname
ORDER BY IF(question IS NULL, 1, 0),
ID ) AS rn_qst
FROM tab
)
SELECT item_id AS ID,
item_id,
name,
surname,
MAX(IF(rn_add = 1, addition, NULL)) AS addition1,
MAX(IF(rn_add = 2, addition, NULL)) AS addition2,
MAX(IF(rn_add = 3, addition, NULL)) AS addition3,
MAX(IF(rn_qst = 1, question, NULL)) AS question1,
MAX(IF(rn_qst = 2, question, NULL)) AS question2,
MAX(IF(rn_qst = 3, question, NULL)) AS question3,
SUM(amount) AS amount
FROM cte
GROUP BY item_id,
name,
surname
Check the demo here.
The dynamic solution aims at reproducing that exact same query as a prepared statement (which is essentially a string that you first build and then ask MySQL to execute over the database), with the only difference that it needs to generalize on the amount of fields to extract:
MAX(IF(rn_add = 1, addition, NULL)) AS addition1,
MAX(IF(rn_qst = 1, addition, NULL)) AS question1,
...
...
MAX(IF(rn_add = <n>, addition, NULL)) AS addition<n>,
MAX(IF(rn_qst = <n>, addition, NULL)) AS question<n>,
And we need to reproduce these instructions n times with n equals to the item_id's highest amount of both addition and question values. In order to generate this piece of query, we get the longest list of indices:
WITH cte AS(
SELECT DISTINCT ROW_NUMBER() OVER(PARTITION BY item_id) AS idx
FROM tab
)
and cycle over it to generate all MAX rows as a string where, in place of the specific number (as in the static query), we will use all the numbers stored inside cte.idx:
SELECT GROUP_CONCAT(
CONCAT('MAX(IF(rn_add = ', cte.idx, ', addition, NULL)) AS addition', cte.idx, ','
'MAX(IF(rn_qst = ', cte.idx, ', question, NULL)) AS question', cte.idx
)) INTO #sql
FROM cte;
Once we have the generalized amonut of MAX rows, we can just use this together with the rest of the static query, which does not depend on the number of addition or question values.
SET #cte = 'WITH cte AS(SELECT *, ROW_NUMBER() OVER(PARTITION BY name, surname ORDER BY IF(addition IS NULL, 1, 0), ID) AS rn_add, ROW_NUMBER() OVER(PARTITION BY name, surname ORDER BY IF(question IS NULL, 1, 0), ID) AS rn_qst FROM tab)';
SET #sql = CONCAT(#cte,
'SELECT item_id AS ID, item_id, name, surname,',
#sql,
',SUM(amount) AS amount FROM cte GROUP BY item_id, name, surname'
);
Once we have the static query generated as a string in a dynamic way, we can ask MySQL to prepare, execute and deallocate it.
PREPARE stmt1 FROM #sql;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
The execution will show you your desired output.
Here's the full code for the dynamic query:
SET #sql = NULL;
WITH cte AS(
SELECT DISTINCT ROW_NUMBER() OVER(PARTITION BY item_id) AS idx
FROM tab
)
SELECT GROUP_CONCAT(
CONCAT('MAX(IF(rn_add = ', cte.idx, ', addition, NULL)) AS addition', cte.idx, ','
'MAX(IF(rn_qst = ', cte.idx, ', question, NULL)) AS question', cte.idx
)) INTO #sql
FROM cte;
SET #cte = 'WITH cte AS(SELECT *, ROW_NUMBER() OVER(PARTITION BY name, surname ORDER BY IF(addition IS NULL, 1, 0), ID) AS rn_add, ROW_NUMBER() OVER(PARTITION BY name, surname ORDER BY IF(question IS NULL, 1, 0), ID) AS rn_qst FROM tab)';
SET #sql = CONCAT(#cte,
'SELECT item_id AS ID, item_id, name, surname,',
#sql,
',SUM(amount) AS amount FROM cte GROUP BY item_id, name, surname'
);
SELECT #sql;
PREPARE stmt1 FROM #sql;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
Check the demo here.
Side Note: if you want to store the output of this query, you may require to create a view inside the prepared statement. In that case you should change the #sql assignment to:
SET #sql = CONCAT('CREATE VIEW my_view AS ',
#cte,
'SELECT item_id AS ID, item_id, name, surname,',
#sql,
',SUM(amount) AS amount FROM cte GROUP BY item_id, name, surname'
);
hence select the content of the view whenever you need it, for example to export it to Excel.

how to convert json data to specific alias and with comma seperated values in mysql

i have one table of product_attributes that is below:-
id attr_details
1 {"Manufacturer":"Lennovo","Warranty":"6 months"}
2 {"Manufacturer":"HP","Warranty":"6 months"}
3 {"Manufacturer":"DEll","Warranty":"12 months","Type":"DDR"}
4 {"Size":"36","Color":"Red","Material":"Fabric"}
My attr_details column data stored in json. My expected Output is like below:-
label values
Manufacturer Lennovo,HP,DEll
Warranty 6 months,12 months
Type DDR
Size 36
Color Red
Material Fabric
The attr_details json is not predefined it can be any userdefined input json. So can anyone help me how to achieve this output.
Try this:
SET #sql = NULL;
SELECT GROUP_CONCAT(CONCAT("SELECT '",colname,":' AS 'Label', GROUP_CONCAT(val)
FROM (SELECT JSON_UNQUOTE(JSON_EXTRACT(attr_details,'$.", colname,"')) AS 'val'
FROM mytable /*you can add the WHERE condition in here*/ GROUP BY val) A
GROUP BY Label") SEPARATOR " UNION ")
INTO #sql
FROM
(WITH RECURSIVE data AS (
SELECT attr_details,JSON_VALUE(JSON_KEYS(attr_details), '$[0]') AS colname, 0 AS idx FROM mytable
UNION
SELECT attr_details,JSON_VALUE(JSON_KEYS(attr_details), CONCAT('$[', d.idx + 1, ']'))
AS colname, d.idx + 1 AS idx FROM data AS d
WHERE d.idx < JSON_LENGTH(JSON_KEYS(attr_details)) - 1
) SELECT colname
FROM data
GROUP BY colname) V;
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
This is the closest I can get. The WITH RECURSIVE .. part I use to list out all the keys as single row value each. That one I was referring to a query from the comment section in the MariaDB documentation. Then I construct the query using combination of CONCAT + GROUP_CONCAT. Lastly, I used prepared statement to execute the query. Here is the final output of #sql:
SELECT 'Color:' AS 'Label', GROUP_CONCAT(val)
FROM (
SELECT JSON_UNQUOTE(JSON_EXTRACT(attr_details,'$.Color')) AS 'val'
FROM mytable GROUP BY val) A
GROUP BY Label UNION
SELECT 'Manufacturer:' AS 'Label', GROUP_CONCAT(val)
FROM (
SELECT JSON_UNQUOTE(JSON_EXTRACT(attr_details,'$.Manufacturer')) AS 'val'
FROM mytable GROUP BY val) A
GROUP BY Label UNION
SELECT 'Material:' AS 'Label', GROUP_CONCAT(val)
FROM (
SELECT JSON_UNQUOTE(JSON_EXTRACT(attr_details,'$.Material')) AS 'val'
FROM mytable GROUP BY val) A
GROUP BY Label UNION
SELECT 'Size:' AS 'Label', GROUP_CONCAT(val)
FROM (
SELECT JSON_UNQUOTE(JSON_EXTRACT(attr_details,'$.Size')) AS 'val'
FROM mytable GROUP BY val) A
GROUP BY Label UNION
SELECT 'Type:' AS 'Label', GROUP_CONCAT(val)
FROM (
SELECT JSON_UNQUOTE(JSON_EXTRACT(attr_details,'$.Type')) AS 'val'
FROM mytable GROUP BY val) A
GROUP BY Label UNION
SELECT 'Warranty:' AS 'Label', GROUP_CONCAT(val)
FROM (
SELECT JSON_UNQUOTE(JSON_EXTRACT(attr_details,'$.Warranty')) AS 'val'
FROM mytable GROUP BY val) A
GROUP BY Label
Demo fiddle
WITH cte AS (
SELECT DISTINCT jsontable.label
FROM test
CROSS JOIN JSON_TABLE( JSON_KEYS(test.attr_details),
'$[*]' COLUMNS ( label VARCHAR(255) PATH '$' )) jsontable
)
SELECT cte.label, GROUP_CONCAT(DISTINCT JSON_EXTRACT(test.attr_details, CONCAT('$.', cte.label))) `values`
FROM cte
CROSS JOIN test
GROUP BY label;
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=ab92deb1dc20eef0f090f841ce2c6cd0

mysql query with grouping and concatenate rows into one row

I have the table in mysql with records:
I've written the sql query:
SELECT COUNT(*) AS number_of_contacts, channel_id, direction
FROM cic_case_contacts
WHERE case_id = 328678
GROUP BY channel_id, direction
and the result looks like:
I would like to obtain something like below(based on above data):
I was trying to obtaining that with sql query by using my_sql_function GROUP_CONCAT but it dosen't work:
SELECT COUNT(*) AS number_of_contacts, channel_id, GROUP_CONCAT(direction SEPARATOR ', ') AS directions
FROM cic_case_contacts
WHERE case_id = 328678 AND id IN(149196, 149195, 149194, 149193, 149192) AND `office_id` = 10
GROUP BY channel_id
ORDER BY channel_id
I would be greateful for help.
You can use GROUP_CONCAT on a sub query as follows:
SELECT channelid, GROUP_CONCAT(
CONCAT(direction, ': ', c)
ORDER BY direction
SEPARATOR ', '
) AS summary
FROM (
SELECT channelid, direction, COUNT(*) AS c
FROM t
GROUP BY channelid, direction
) x
GROUP BY channelid
Or simply use conditional aggregation:
SELECT channelid, CONCAT_WS(', ',
CONCAT('in: ', COUNT(CASE WHEN direction = 'in' THEN 1 END)),
CONCAT('out: ', COUNT(CASE WHEN direction = 'out' THEN 1 END))
) AS summary
FROM t
GROUP BY channelid
You can use Concat in MySQL
drop table if exists Demo;
CREATE TABLE Demo
(
ID INT AUTO_INCREMENT PRIMARY KEY,
channelid int,
Name VARCHAR(20)
);
INSERT INTO Demo(channelid, Name)VALUES
(1,'in'),(1,'out'),(1,'in'),(1,'out'),(2,'in'),(2,'out'),(1,'in'),(1,'out'),(1,'in'),(2,'out'),(2,'in'),(2,'out'),(2,'in'),(1,'in'),(1,'in');
Query
SELECT SQL_CALC_FOUND_ROWS
channelid,
group_concat ( concat(name,':',channelid) )
FROM Demo
group by channelid;
SELECT FOUND_ROWS();
See the results the the fiddle
Please find below working code as per your requirement :
select tb.channelid, group_concat
(
concat(tb.name,':',tb.MyCol2Count)
) as v1
from
(Select tbl.channelid,tbl.name,(LENGTH(tbl.val) - LENGTH(REPLACE(tbl.val,",","")) + 1) AS MyCol2Count
from
(SELECT channelid, group_concat
(
concat(name,':',channelid)
) as val,name
FROM Demo
group by channelid,Name) as tbl) as tb group by tb.channelid
You can check on below screenshot : http://springinfosoft.com/code/Groupby_code.png

Single Table MySQL Pivot with Dynamic Column

I want to transform row of mysql table to column, through mysql pivot table
My input table.
My input table which has data in below format.
Area Status User
-----------------------
1 Active user1
1 Failed user2
1 Success user4
2 Active user2
2 Failed user3
2 Success user4
My Desired Output Format is below
Status user1 user2 user3 user4
-----------------------------------------
Active 1 1 0 0
Failed 0 1 1 0
Success 0 0 0 2
Since i do not know the exact number of users i want to pivot it through dynamic column only.
in your case, if you have a separate user table, you can easily make a Cartesian Product between your user table and status table, and make pivoting.. if you need further helps let me know..
have look on one of my following blog post about a pivoting schenerio for sales report, I am using a dynamic calendar table to produce Cartesian Product with Order Category table..
Sample Pivoting and Cartesian Product
I have another runnable example for you, from
product_id supplier_id number price
p1 s1 2 2.12
p1 s2 3 3.12
p2 s1 4 4.12
to
product_id supplier_id1 supplier_id2 number1 number2 price1 price2
p1 s1 s2 2 3 2.12 3.12
p2 s1 NULL 4 NULL 4.12 NULL
here the "supplier_id" is dynamic, it could be one little data set from a 1 million big set.so there could be supplier1,or supplier99,or supplier999,depends on whats in the source table.
first, lets create the source table:
CREATE TABLE test
(
product_id varchar(10),
supplier_id varchar(10),
number int(11),
price decimal(10,2)
);
INSERT INTO test (product_id, supplier_id, number, price) VALUES ('p1', 's1', 2, 2.12);
INSERT INTO test (product_id, supplier_id, number, price) VALUES ('p1', 's2', 3, 3.12);
INSERT INTO test (product_id, supplier_id, number, price) VALUES ('p2', 's1', 4, 4.12);
I don't think one select will do it, so the temp table and column are needed, this code is what you need:
DROP TABLE IF EXISTS final_data;
DROP TABLE IF EXISTS temp_data;
CREATE TEMPORARY TABLE temp_data
SELECT
product_id,
IF(#productid = product_id, #rownum := #rownum + 1, #rownum := 1) seller_number,
#productid := product_id,
supplier_id,
number,
price
FROM
test
CROSS JOIN (SELECT #rownum := 0) r
CROSS JOIN (SELECT #productid:="") n
ORDER BY
product_id ASC;
ALTER TABLE temp_data ADD PRIMARY KEY(product_id, seller_number);
ALTER TABLE temp_data ADD INDEX (seller_number);
#Dynamic Pivot starts via prepared statements
#Step 1: Dynamily create colum names for sql
#Field supplier_id
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
' MAX(IF( seller_number= ''',
seller_number,
''', supplier_id, NULL)) AS ',
CONCAT("supplier_id", seller_number)
)
) INTO #sql
FROM temp_data;
#Field number
SELECT
CONCAT(#sql, ', ',
GROUP_CONCAT(DISTINCT
CONCAT(
' MAX(IF( seller_number= ''',
seller_number,
''', number, NULL)) AS ',
CONCAT("number", seller_number)
)
) )INTO #sql
FROM temp_data;
#Field price
SELECT
CONCAT(#sql, ', ',
GROUP_CONCAT(DISTINCT
CONCAT(
' MAX(IF( seller_number= ''',
seller_number,
''', price, NULL)) AS ',
CONCAT("price", seller_number)
)
) )INTO #sql
FROM temp_data;
#Step 2: Add fields to group by query
SET #sql = CONCAT(' create table final_data as (SELECT
product_id,
', #sql, '
FROM
temp_data
GROUP BY
product_id) ');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DROP TABLE IF EXISTS temp_data;

MYSQL - How to seperate values into columns - concat

Currently I have the following mysql code entered in phpmyadmin:
select Product_ID, group_concat(`Name` separator ',') as `Spec`
from
(
select Product_ID, concat(`Name`, ':',
group_concat(`Value` separator ',')) as `Name`
from product_spec_list
group by Product_ID, `Name`
) tbl
group by Product_ID
Which produces:
ID Name
3 Shielded:0,Type:General Purpose
4 Shielded:0,Type:General Purpose
etc. with a long list of Product IDs with the Names and Values separated by : and ,.
How do I separate the Values into Columns named by 'Name'?
E.g.
ID Shielded Type
3 0 General Purpose
4 0 General Purpose
There's about 40 different Names of values.
Thanks for any help
I haven't tested it, but I am thinking something like this:
SELECT Product_ID AS `ID`
, GROUP_CONCAT(IF(Name="Shielded", values, "") SEPARATOR "") AS `Shielded`
, GROUP_CONCAT(IF(Name="Type", values, "") SEPARATOR "") AS `Type`
FROM
(SELECT Product_ID, Name, GROUP_CONCAT(value SEPARATOR ',') AS values
FROM product_spec_list
GROUP BY Product_ID, Name
) AS subQ
GROUP BY Product_ID;