How to fetch row value as a column name In Mysql - mysql

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

Related

How to make a pivot like sql result [duplicate]

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

Mysql Pivot some column in 1 table [duplicate]

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:

Prepared Statement: Crosstab dynamic mysql query

I am trying to make a cross tab pivot table. I need to get all teams from the database table dynamically on separate columns instead of specifying names of the teams in the query which I am currently doing. I have looked at another example i.e. MySQL pivot table query with dynamic columns.
At the moment I am receiving the results fine from the database but only by manually typing what column I need in the query. See the example below:
SELECT IFNULL(DATE( date_posted ), 'Total') AS DATE,
SUM(CASE WHEN added_by LIKE '%Team One%' THEN 1 ELSE 0 END) AS Team1,
SUM(CASE WHEN added_by LIKE '%Team Two%' THEN 1 ELSE 0 END ) AS Team2,
COUNT( added_by ) AS Daily_Total FROM teamdata WHERE status LIKE
'%completed%' GROUP BY IFNULL(DATE( date_posted ), 'Total') DESC WITH ROLLUP;
Which displays 4 columns of DATE, Team1, Team2 and Daily_Total. But at a later stage there will be more columns to add in but to be done dynamically. I am trying to execute this prepared statement but to no success:
SET #sql = NULL;
SELECT GROUP_CONCAT( DISTINCT
CONCAT(
'sum(CASE WHEN added_by = ''',
added_by,
''' THEN 1 else ''-'' END) AS `', added_by,
'`'
)
) into #sql
FROM teamdata;
SET #sql
= CONCAT('SELECT IFNULL(DATE( date_posted ), \'Total\') AS DATE, ', #sql, '
from teamdata
WHERE status = \'completed\'
GROUP BY IFNULL(DATE( date_posted ), \'Total\') DESC WITH ROLLUP');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Please could I get further help on this.

How to match column names and values from joining and related tables?

I have the following DB structure:
cars:
id
make
features:
id
name
cars_feature:
id
car_id
feature_id
value
I want to be able to select all cars with all features and return results with feature.name as the column name and cars_feature.value as the value. Right now I am able to get all feature and all values but I only figured out how to do that with group_concat.
What I am looking for is the following output:
car_id car_make color wheels doors
1 Ford blue alloy
2 Audi alloy 3
Data example: SQLFiddle
The following is a modified version of code that I found at Combine multiple rows into one row MySQL.
SET #sql = NULL;
SELECT GROUP_CONCAT(DISTINCT CONCAT(
'MAX(CASE WHEN `name` = ''',
`name`,
''' THEN value END) AS `',
`name`, '`'
)
) INTO #sql
FROM (SELECT name,
value
FROM features, car_feature
WHERE features.id = car_feature.feature_id) AS car_features_feature;
SET #sql = CONCAT('SELECT car_feature.car_id AS car_id,
cars.make AS car_make,
',
#sql,
'
FROM car_feature
LEFT JOIN cars ON car_feature.car_id = cars.id
LEFT JOIN features ON car_feature.feature_id = features.id
GROUP BY car_id;');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Thank you for the learning experience.

Group by and additional columns for each language/translation of product name

If I have these data in MySQL database:
PID LANG TRANS
1 EN Apple
1 DE Apfle
I want to get results in sql:
PID EN_TRANSLATION DE_TRANSLATION
1 Apple Apfle
How to do this? I already have tables and everything but need help writing query that will give me columns per language per result for each product.
NOTE: I don't know set of language(s) ! It can be EN, DE or whatever else..
Thx!
If you have known set of LANG then you can use the following technique to generate the pivot view
select
PID,
max(case when LANG = 'EN' then TRANS end) as EN_TRANSLATION,
max(case when LANG = 'DE' then TRANS end) as DE_TRANSLATION
from table_bame
group by PID
If the LANG values are unknown then you need to use dynamic sql for this as
set #sql = null;
select
group_concat(distinct
concat(
'max(case when LANG = ''',
LANG,
''' then TRANS end) AS ',
concat(LANG,'_TRANSLATION')
)
) into #sql
from table_name ;
set #sql = concat('select PID, ', #sql, ' from table_name
group by PID
');
prepare stmt from #sql;
execute stmt;
deallocate prepare stmt;
http://www.sqlfiddle.com/#!9/95d29/1