my query :
set #sql = NULL;
select
group_concat(distinct
concat(
'max(if(first.study = ''',
study, ''', first.avg_scores, NULL)) as ',
study
)
) into #sql
from `table`;
SET #sql = concat('select first.name,
', #sql, '
from `table` first
join `table` second
on first.name = second.name
group by first.name');
prepare stmt from #sql;
execute stmt;
deallocate prepare stmt;
when data in column "study"
=================================
name | study | avg_scores
=================================
alfa c 75
beta c 70
alfa php 85
beta php 90
and result : its true.
===========================
name | c | php
===========================
alfa 75 85
beta 70 90
the problem when i have data in table like this :
===================================
name | study | avg_scores
===================================
alfa junior c 75
beta junior c 70
alfa junior php 85
beta junior php 90
error :
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near 'c,max(if(first.study = 'junior php',
first.avg_scores, NULL)) as junior php ' at line 2: prepare stmt from #sql"
so : how to fix my query ?
The problem is that you need to escape the identifiers, because a column name cannot have a space. The following uses double quotes for the name (you can also use backticks):
set #sql = NULL;
select group_concat(distinct concat('max(if(first.study = ''', study,
''', first.avg_scores, NULL)) as "', study, '"'
---------------------------------------------------------------------^ ----------^
)
) into #sql
from `table`;
SET #sql = concat('select first.name, ', #sql, '
from `table` first join `table` second on first.name = second.name
group by first.name');
Related
I have following tables
demographic_categories
demographic_id demographic_name
1 color
2 age_group
project_tests
test_id group_id project_id
1 1 1
2 1 1
test_demographic_requirements
test_id project_id demgraphic_id demographic_value
1 1 1 blue
1 1 2 young
2 1 1 green
2 1 2 middle
And I need a query which would give me following result :
test_id group_id color age_group
1 1 blue young
2 1 green middle
I guess we need to use concept of pivot table to get the result, but I am unable to. And I demographic categories can we might be same they tend to change so I need something dynamic so what would be the best way to do it ?
I have tried doing the following based of previous similar questions but it doesn't seems to work for me, here is what I have tried:
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when dc.demographic_name = ''',
demographic_name,
''' then trd.demographic_value end) AS ',
replace(demographic_name, ' ', '')
)
) INTO #sql
from demographic_categories;
SET #sql = CONCAT('SELECT pt.test_id, pt.group_id,
', #sql,'
from test_requirement_demographic trd
LEFT JOIN demographic_categories dc ON trd.demographic_id = dc.demographic_id
LEFT JOIN project_tests pt ON pt.test_id = trd.test_id and project_id =1
group by pt.test_id;');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Your dynamic SQL is just fine except for one thing. It has an ambiguous column project_id on your second left join, Just replace it with pt.project_id or trd.project_id and it will give desired result.
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when dc.demographic_name = ''',
demographic_name,
''' then trd.demographic_value end) AS ',
replace(demographic_name, ' ', '')
)
) INTO #sql
from demographic_categories;
SET #sql = CONCAT('SELECT pt.test_id, pt.group_id,
', #sql,'
from test_demographic_requirements trd
LEFT JOIN demographic_categories dc ON trd.demographic_id = dc.demographic_id
LEFT JOIN project_tests pt ON pt.test_id = trd.test_id and pt.project_id =1
group by pt.test_id;');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I ran it on a rextester. Here is the link : dynamic_pivot_test
This question already has answers here:
MySQL - Rows to Columns
(13 answers)
MySQL pivot table query with dynamic columns
(3 answers)
Closed 4 years ago.
I have a table like this:
id key year month value
---------------------------------------
1 AD 2000 1 5465
2 AD 2000 2 6445
3 JK 2000 1 7777
4 JK 2000 2 9999
I need to retrive the values like this:
key 2000-1 2000-2
------------------------
AD 5465 6445
JK 7777 9999
I'm having issues with creating the headers, concatenating year and month and displaying the value under the header.
I have another pivot procedure like this:
SELECT
GROUP_CONCAT(
DISTINCT CONCAT(
'MAX(IF(combustible_id = ''',
combustible_id,
''', valor_combustible, NULL)) AS ',
CONCAT("`",admin_combustibles.nombre,"`")
)
) INTO #SQL
FROM
admin_indice_combustibles
INNER JOIN admin_combustibles
ON admin_indice_combustibles.combustible_id = admin_combustibles.id_combustible
WHERE admin_indice_combustibles.estado = 1;
SET #SQL = CONCAT(
'SELECT anio, mes, ',
#SQL,
' FROM admin_indice_combustibles
WHERE estado = 1
GROUP BY anio, mes
ORDER BY id_indice_combustible'
);
PREPARE stmt
FROM
#SQL;
it is working, but it uses more data (because it has a JOIN with another table), now is easier, all the data is in just 1 table, but I can't get it. any hint please?
EDIT:
I'm trying with this code:
BEGIN
SELECT
GROUP_CONCAT(
DISTINCT CONCAT(
' MAX(IF(anio = ''',
DIST.anio,
''' AND mes = ''', DIST.mes, ''', energia_adjudicada_mwh, NULL)) AS ',
CONCAT("`",DIST.anio,"-`", DIST.mes,"`")
)
) INTO #SQL
FROM
admin_contratos_energia_adjudicadas_distribucion_mensual AS DIST
WHERE DIST.activo = 1;
SET #SQL = CONCAT(
'SELECT DIST.key, DIST.contrato_id ',
#SQL,
' FROM admin_contratos_energia_adjudicadas_distribucion_mensual AS DIST
WHERE activo = 1
GROUP BY DIST.key
ORDER BY DIST.contrato_id ');
PREPARE stmt
FROM
#SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
I'm getting the error:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'MAX(IF(anio = '2016' AND mes = '1', energia_adjudicada_mwh, NULL)) AS 2016-1`,' at line 1
I just need to concatenate the year (anio) and month (mes) in the header, and give the value (energia_adjudicada_mwh) to them, for each year and mont, group by key...
This is the table that I have and the table that I need:
Use conditional aggregation like this:
SQL DEMO
SELECT `key`,
MAX( CASE WHEN `year` = 2000 and `month` = 1 THEN `value` END) as `2000-01`,
MAX( CASE WHEN `year` = 2000 and `month` = 2 THEN `value` END) as `2000-02`
FROM t49613951
GROUP BY `key`;
OUTPUT:
I have a table of data which some of data looks like below.
Table name Uk_Small_Stage1
name created 1m
IA UK Smaller Companies 17/10/2017 3.9
Jupiter UK Smaller Companies I Acc 17/10/2017 6.96
Old Mutual UK Smaller Companies Focus R Inc GBP 17/10/2017 2.19
TB Amati UK Smaller Companies B Acc 17/10/2017 4.85
TM Cavendish AIM B 17/10/2017 2.34
I want to pivot the table to look like
Created IA UK Smaller Companies Jupiter UK Smaller Companies I Acc Old Mutual UK Smaller Companies Focus R Inc GBP
17/10/2017 3.9 6.96 2.19
(a column should appear for each row against the field "name".
The Uk_Small_Stage1 has multiple records for each date.
I am trying to use the code below which should dynamically build and execute the pivot but am getting mysql errors.
Could any one help please?
SET group_concat_max_len=2048;
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(name = ''',
name,
''', 1m, NULL)) AS ‘,
CONCAT("`”,name,"`")
)
)
) INTO #sql
FROM UK_Small_Stage1;
SET #sql = CONCAT('SELECT created, ', #sql, ' FROM UK_Small_Stage1 GROUP BY created’);
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Latest code
SET group_concat_max_len=2048;
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(name = ''',
name,
''', 1m, NULL)) AS ‘,
CONCAT(''',name,''')
)
)
) INTO #sql
FROM UK_Small_Stage1;
SET #sql = CONCAT('SELECT created, ', #sql, ' FROM UK_Small_Stage1 GROUP BY created’);
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I need help with below scenario. How can we get distinct values in rows as column Names dynamically?
I have data in below format..
Sno firstName Subject Marks
1 ABC Eng 10
2 PQR Hindi 20
3 LM Telgu 20
4 LM Hindi 20
5 LM Eng 39
I need output in below format.
Sno FirstName Eng Hindi Telgu
1 ABC 10 Null Null
2 PQR Null 20 Null
3 LM 39 20 20
If one more subject is added, query should be written dynamic enough to include those values too..
How can Write Query for This?
Hi there as Abecee told you in comment solution for your problem is pivoting table.
Here is query for your table
SELECT Sno, firstName,
SUM(CASE WHEN Subject = 'Eng' THEN Marks ELSE NULL END) AS Eng,
SUM(CASE WHEN Subject = 'Hindi' THEN Marks ELSE NULL END) AS Hindy,
SUM(CASE WHEN Subject = 'Telgu' THEN Marks ELSE NULL END) AS Telgu
FROM t1
GROUP BY firstName
ORDER BY Sno
And here is SQL Fiddle to see how it's work...
GL!
Edit:
Ok based on this bluefeet answer here is dynamics solution for your problem
SET #sql = NULL;
SELECT GROUP_CONCAT(DISTINCT
CONCAT('SUM(CASE WHEN Subject = ''',
Subject,
''' THEN Marks ELSE NULL END) AS ',
REPLACE(Subject, ' ', ''))) INTO #sql
FROM t1;
SET #sql = CONCAT('SELECT Sno, firstName, ', #sql, '
FROM t1
GROUP BY firstName
ORDER BY Sno');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
First part of this
SET #sql = NULL;
SELECT GROUP_CONCAT(DISTINCT
CONCAT('SUM(CASE WHEN Subject = ''',
Subject,
''' THEN Marks ELSE NULL END) AS ',
REPLACE(Subject, ' ', ''))) INTO #sql
FROM t1;
is to dynamically create this part of first query I wrote
SUM(CASE WHEN Subject = 'Eng' THEN Marks ELSE NULL END) AS Eng,
SUM(CASE WHEN Subject = 'Hindi' THEN Marks ELSE NULL END) AS Hindy,
SUM(CASE WHEN Subject = 'Telgu' THEN Marks ELSE NULL END) AS Telgu
the second part is to create prepared statement and to include dynamically created part into this
SELECT Sno, firstName,
-- here you add dynamically created part #sql
FROM t1
GROUP BY firstName
ORDER BY Sno
you do that with CONCAT in this part of code
SET #sql = CONCAT('SELECT Sno, firstName, ', #sql, '
FROM t1
GROUP BY firstName
ORDER BY Sno');
when you create that from that string you prepare statement and execute it
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Hope that is a little bit clear now...
Here is SQL Fiddle so you can see that you can compare both query and see how it's work..
GL!
P.S. if you have any question fill free to ask in comment bellow
I have below database table : Table name - dim_module
id Creation_Date Goals Alternative Value
-----------------------------------------------------------
1 2014-04-17 10:09:30 G1 A 0.86
2 2014-04-17 10:09:30 G1 B 0.87
3 2014-04-17 10:09:30 G2 A 0.5
4 2014-04-17 10:09:30 G2 B 0
I am using below procedure for getting desired output
CREATE DEFINER=`root`#`localhost` PROCEDURE `stmt`()
BEGIN
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(goals = ''',
goals,
''', round(value, 2), NULL)) AS ',
goals
)
) INTO #sql
FROM sgwebdb.dim_module;
SET #sql = CONCAT('SELECT alternative, ', #sql, ' FROM sgwebdb.dim_module GROUP BY alternative');
prepare stmt from #sql;
But if Dim_Module don't have any row then procedure is not take care and I am getting error.
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL' at line 1
Please help to take care of empty table.
Maybe because #sql is null.
Try setting it to some value with IFNULL
SET #sql = CONCAT('SELECT alternative, ', IFNULL(#sql,'somecolumnor*here'), ' FROM sgwebdb.dim_module GROUP BY alternative');
Or detect that #sql is null and do something else.
You may check #sql before using it within your second SELECT:
IF #sql
THEN
SET #sql = CONCAT('SELECT alternative, ', #sql, ' FROM sgwebdb.dim_module GROUP BY alternative');
prepare stmt from #sql;
END IF;