Create an insert to pivot value pair values into a table - mysql

I have a value pair table that I want to use to create a member table
Based on Taryns answer to this question
MySQL pivot table query with dynamic columns
I have this code that creates selects the data, which works fine
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(CASE WHEN wpdg_usermeta.meta_key = ''',
meta_key,
''' THEN wpdg_usermeta.meta_value END) `',
meta_key, '`'
)
) INTO #sql
FROM
wpdg_usermeta
WHERE
wpdg_usermeta.meta_key like "member_%"
;
SET #sql = CONCAT('SELECT user_id, ', #sql, '
FROM wpdg_usermeta
GROUP BY user_id');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
So, my question is - does anyone know how I could alter this to run an INSERT instead of a SELECT so that I could populate the new member table?

You want to create a new table with the results of the dynamic query. I think the simplest approach is to use the create table ... as select ... syntax.
This requires very few changes to your code, and allow you to create the table on the fly based on the results of the query:
SET #sql = CONCAT(
'CREATE TABLE member AS SELECT user_id, ',
#sql,
' FROM wpdg_usermeta GROUP BY user_id'
);
Note that the datatypes of the new table are inferred from the query's metadata; this might, or might no, to exactly what you want. You can check the documentation for more detaiils.

Related

How to pivot columns to rows in MySQL for N number of columns without using Union all

I already went through the details in the link (Mysql Convert Column to row (Pivot table )). As the number of Columns is high and using union all on all of them would be time taking. I decided to use the last resolution in the given link. I was able to run the query the results were:
The issue is the acct getting included as data and also I want to create a table from the result . So Can these entries be excluded and how can I create a table from the results? (new to SQL)
The Code:
SET SESSION group_concat_max_len = 92160;
SET #target_schema='rd';
SET #target_table='pbc_gl';
SET #target_where='`acct`';
SELECT
GROUP_CONCAT(qry SEPARATOR ' UNION ALL ')
INTO #sql
FROM (
SELECT
CONCAT('SELECT `acct`,', QUOTE(COLUMN_NAME), ' AS `Business_Unit`,`', COLUMN_NAME, '` AS `value` FROM `', #target_table, '` WHERE ', #target_where) qry
FROM (
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`=#target_schema
AND `TABLE_NAME`=#target_table
) AS `A`
) AS `B` ;
PREPARE s FROM #sql;
EXECUTE s;
DEALLOCATE PREPARE s;

Debugging MySQL pivot row into dynamic number of columns

I recently came across the thread below, and it was very useful in building a dynamic SQL for MySQL.
MySQL pivot row into dynamic number of columns
With that said, I did struggle with trying to debug the statement. Now for the real purpose of this post! To debug, I would run a Select on my variable containing the statement (Select #SQL). Then copy that result from the viewer windows and have the query analyzer review it. Once I did this, development really sped up. I am sure this is known by all the advance pro developers but for any newbies, I hope this help!
My dynamic statement looks like this as a reference.
SET #sql = NULL;
SET ##group_concat_max_len = 50000;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
' sum(
case when symbol = ''',
symbol,
''' then pctttlassets end) AS ',
CONCAT(UPPER(ACode),'_',REPLACE(Symbol, '+', ''))
)
) INTO #sql
from trade_detail this;
SET #sql = CONCAT('SELECT Distinct(main.port_code) as PortCode, ', #sql, '
FROM trade_detail main GROUP BY main.Port_Code');
SELECT #SQL;
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Limit the columns displayed in a MYSQL pivot table

The Question:
How do I limit the number of columns displayed/produced on a MYSQL pivot table?
My Setup:
I have a table named "updates" that looks like the following:
I have the following snippet of query (This is only part of the query, the whole thing only adds more columns from other tables but this is the only section that gets pivoted):
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(Date = ''',
Date,
''', Description, NULL)) AS ',
CONCAT("'",Date_Format(Date, '%d/%m/%Y'),"'")
)
)INTO #sql
FROM updates;
SET #sql = CONCAT('SELECT Action, ', #sql, ' FROM updates GROUP BY Action');
PREPARE stmt FROM #sql;
EXECUTE stmt;
The result of this query is as follows:
As you can see, this pivots the table as intended with the dates as columns. However, there is potential for these updates (to actions) to become very long before they are "closed" and not displayed. Therefore, I would like to limit the outcome to the latest 3 updates. BUT..Not per action as this would potentially still give me a lot of updates in the pivot table.
I would like to have the most recent 3 dates from the updates table with all updates for each date keeping this pivot format.
Example: The outcome table above would look the same but with the exception of the columns titled "02/10/2016" and "04/10/2016".
Thanks in advance for any assistance or advise.
For anyone else trying to solve this issue, I managed to use the following query to produce the desired results:
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(Date = ''',
Date,
''', Description, NULL)) AS ',
CONCAT("'",Date_Format(Date, '%d/%m/%Y'),"'")
) ORDER BY Date ASC
) INTO #sql
FROM (
SELECT * FROM updates
GROUP BY Date
ORDER BY Date DESC
LIMIT 2)
AS updates;
SET #sql = CONCAT('SELECT Action, ', #sql, ' FROM updates GROUP BY Action');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

use result string from one table as column names for another query

I am trying to trying to simplify the following query :-
SELECT id, m_field_id_46 AS Liverpool,m_field_id_47 AS London,m_field_id_48 AS Belfast FROM member_data
In a way i can dynamically create the column names
SELECT id, (SELECT GROUP_CONCAT('m_field_id_',m_field_id,' AS ',m_field_label) FROM member_fields) as dist FROM member_data
However this is not working. Please help
i got it working by looking at another answer from stackoverflow: -
SET #listStr = ( SELECT GROUP_CONCAT('md.m_field_id_',m_field_id,' AS `',m_field_label,'`') FROM member_fields );
SET #query := CONCAT('SELECT ', #listStr, ' FROM member_data');
PREPARE STMT FROM #query;
EXECUTE STMT;

SQL query to find duplicate rows, in any table in Mysql database

I'm looking for a schema-independent query. The query should be equally capable of catching duplicate rows in either table in a database.I have number of tables without primary key. I have found a result for sql server [which i have most experience] but looking for same thing in mysql
Use dynamic SQL to generate the query using the column information in information_schema:
SET #tablename = 'yourTable';
SET #sql = (
SELECT CONCAT('SELECT *
FROM `', table_name, '`
GROUP BY ', GROUP_CONCAT(CONCAT('`', column_name, '`')), '
HAVING COUNT(*) > 1')
FROM information_schema.columns
WHERE table_name = #tablename );
PREPARE stmt FROM #sql;
EXECUTE stmt;