MySql pivot table dynamic columns - mysql

I've got the following tables in my database:
this is the table km_kondomanager_millesimal_table_values
this is the table km_kondomanager_millesimal_table
The two tables are joined together by km_kondomanager_millesimal_table_value_table_id and km_kondomanager_millesimal_table_id
I've managed to creat a pivot table using the followinf query:
SELECT km_kondomanager_millesimal_table_value_building_id
,SUM(CASE WHEN km_kondomanager_millesimal_table_value_table_id = 9
THEN km_kondomanager_millesimal_table_millesimal_value END) tabella_gruppo_A
,SUM(CASE WHEN km_kondomanager_millesimal_table_value_table_id = 10
THEN km_kondomanager_millesimal_table_millesimal_value END) tabella_gruppo_B
FROM km_kondomanager_millesimal_table_values
WHERE km_kondomanager_millesimal_table_value_group_id = 15
GROUP BY km_kondomanager_millesimal_table_value_building_id
and this is how it looks like:
My problem is that I need to take the table name from km_kondomanager_millesimal_table and use it as column, these columns are not always the same as you can see in the immage there are other stored in the database. The query I've created requires to specify km_kondomanager_millesimal_table_value_table_id in the case and also to specify the column name in the example tabella_gruppo_A and tabella_gruppo_B. Can anyboby help me to achieve this? Also I need to convert the pit table to HTML table. Many thanks

I've managed to get it sorted using mysql stored procedure and this is the code:
BEGIN
SELECT
GROUP_CONCAT(
CONCAT("MAX(IF(km_kondomanager_millesimal_table_value_table_id='", km_kondomanager_millesimal_table_value_table_id, "',km_kondomanager_millesimal_table_millesimal_value ,NULL)) AS '", km_kondomanager_millesimal_table_name, "'"), "
"
)INTO #answers
FROM (
SELECT DISTINCT km_kondomanager_millesimal_table_value_table_id, km_kondomanager_millesimal_table_name FROM km_kondomanager_millesimal_table_values INNER JOIN km_kondomanager_millesimal_table
ON km_kondomanager_millesimal_table_values . km_kondomanager_millesimal_table_value_table_id = km_kondomanager_millesimal_table. km_kondomanager_millesimal_table_id WHERE km_kondomanager_millesimal_table_value_group_id = 13
) A;
SET #query :=
CONCAT(
'SELECT km_kondomanager_millesimal_table_value_building_id, ', #answers,
' FROM km_kondomanager_millesimal_table_values WHERE km_kondomanager_millesimal_table_value_group_id = 13 GROUP BY km_kondomanager_millesimal_table_value_building_id'
);
PREPARE statement FROM #query;
EXECUTE statement;
END

Related

Auto increment temporary column in select statement MySQL 8

Hello i use this type of sentence to return an auto increment column in my prepared statement selects
cnt := cnt + 1
SET #query = CONCAT('SELECT * FROM (SELECT (#cnt := #cnt + 1) AS id, a.idProducto idProducto, a.idExProducto idExterno, trim(a.descripcion) nombreProducto, trim(a.descripcionAlt) nombreLargoProducto, trim(a.serial) serial,',
' a.peso, a.volumen, a.IdTpoGrupo, trim(b.descripcion) nombreGrupo,',
' a.idTpoLinea, trim(c.descripcion) nombreLinea,',
' a.idTpoMarca, trim(d.descripcion) nombreMarca,',
' a.idTpoUnidad, trim(e.descripcion) nombreTipoUnidad,',
' CASE WHEN a._estado = 1 THEN ''true'' ELSE ''false'' END estado, ',
' g.nombreArchivo imagen ',
' FROM tblProducto a',
' INNER JOIN tblProducto_TpoGrupo b ON a.IdTpoGrupo = b.IdTpoGrupo',
' INNER JOIN tblProducto_TpoLinea c ON a.idTpoLinea = c.idTpoLinea',
' INNER JOIN tblProducto_TpoMarca d ON a.idTpoMarca = d.idTpoMarca',
' INNER JOIN tblTpoUnidadMedida e ON a.idTpoUnidad = e.idTpoUnidadMed ',
' LEFT JOIN tblProductoXImagen f ON a.idProducto = f.idProducto AND f._estado=1',
' LEFT JOIN tblImagen g on f.idImagen = g.idImagen AND g._estado=1',
' WHERE a._estado<2 ',whereLike,whereConcat, ' order by idProducto ) allrecords');
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
that works perfect on MySQL 5, but now in MySQL 8 is deprecated and my transaction return a warning, but the warning stop the execution of my stored procedure, i want to know if there is a solution to can achieve this behavior in MySQL 8.
Thanks for your help.
You can use window functions. The logic you sem to want is:
row_number() over(order by idProducto) as id
This gives you an incrementing integer value, that starts at 1 and increments according to idProducto. If two rows in the resultset have the same idProducto, it is undefined which one will be ordered "first" (it is, however, guaranteed that they will not get the same row number) - in that case, you might want to add one or more columns to the order by clause, so you do get a predictable, stable result.

How to get multiple value in one variable with ' '

How i can get value like this in a variable 'TFSEP-2019','TFjul-2018','TFJun-2018' without spaces.
SELECT s.house, s.grade, s.homeroom AS Campus
FROM student s,fees_jrl f
WHERE s.studnum = f.studnum AND
f.name IN (' TFJun-2018 TFJul-2018 ') AND
f.trans_type= 'chg' AND
f.paid_id is NULL AND s.house LIKE '%'
GROUP BY s.house
I am getting like this ('TFJun-2018 TFJUL-2018 TFSEP-2019') but I want like ('TFSEP-2019','TFjul-2018','TFJun-2018') please help
You may refer the following statements with like operators, whenever you need quotes('), use doubled-quotes('') :
create table tab ( Id int, expression varchar(100));
insert into tab values(1 ,'TFJun-2018 TFJUL-2018 TFSEP-2019');
insert into tab values(2,'''TFJun-2018'',''TFJUL-2018'',''TFSEP-2019''');
select * from tab where expression like '''TFJun-2018''%';
Id expression
2 'TFJun-2018','TFJUL-2018','TFSEP-2019'
or
select * from tab where expression like '''TFJun-2018'',''TFJUL-2018''%';
Id expression
2 'TFJun-2018','TFJUL-2018','TFSEP-2019'
or
select * from tab where expression like '''TFJun-2018'',''TFJUL-2018'',''TFSEP-2019''%';
Id expression
2 'TFJun-2018','TFJUL-2018','TFSEP-2019'
Rextester Demo
You can use like for strings
% means any chars, _ means one char
So doing
F.name like %2018%
Will give you all of 2018..
use explicit join and concat
SELECT
concat( concat( concat( concat("'",s.house),"'"),concat( concat("'",s.grade),"'")),
concat( concat("'",s.homeroom),"'"))
FROM student s join fees_jrl f
on s.studnum = f.studnum
where f.name IN (' TFJun-2018 TFJul-2018 ') AND
f.trans_type= 'chg' AND
f.paid_id is NULL AND s.house LIKE '%'
I think you dont need group by as you have no aggregation function

UPDATE multiple table with same column name with condition for each value on MYSQL

I've a column "pid" and a lot of table on each database , then I want to update all table from every database with column "pid" and set 'pid' = 5 where 'pid' = 3 and set 'pid' = 6 where 'pid = '7' on 1 query .
I've find post like this and try to apply it:
Select 'UPDATE ' + TABLE_NAME + ' SET pid = ''5'' '
From INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'pid'
Without condition for try it , then MYSQL just return me a select with value 0 .
'UPDATE ' + TABLE_NAME + ' SET pid = ''5'' '
0
Need a little help and explain for make this query work and understand how its work .
Really thanks everyone :)
UPDATE table_name
SET pid = 5
WHERE pid = 3;
It should be implemented like this. You simply tell to update the table named table_name to set pid as '5' wherever it finds it as '3'.
Read also here. ;)

SQL returning string instead table

I am having this SQL command:
Select company, purchases.stock,SUM(ammount)*price from purchases INNER JOIN curstock ON purchases.stock = curstock.stock Group by company , purchases.stock;
Which returns following table :
Is it possible that it would print instead of table strings like:
"Company XXX owns YYY in ZZZ stock."
or SQL does not provide such formatting and it has to be done in code.
You can use CONCAT() function
SELECT CONCAT('Company ', company, ' owns ', SUM(ammount)*price, ' in ', purchases.stock, ' stock.') AS value
FROM purchases
INNER JOIN curstock
ON purchases.stock = curstock.stock
GROUP BY company , purchases.stock;

How to Concat data using COALESCE in MySql

This is my SQL query
DECLARE #strManualRefundIdList AS VARCHAR(MAX)
SELECT #strManualRefundIdList = COALESCE(#strManualRefundIdList + '|', '') + CONVERT(VARCHAR(MAX), ManualRefund_strReasonCode)
FROM tblManualRefunds WHERE ManualRefund_lngId IN ( 20 ,21 ,22 )
SELECT #strManualRefundIdList;
This gives like pivot, all the rows concatenated in a single row.
The Same i need to convert into MySql Query.
I tried like this
SELECT
CONCAT(COALESCE(CONCAT(v_strManualRefundIdList, '|'), '') , ( ManualRefund_lngId))
INTO
v_strManualRefundIdList
FROM tblManualRefunds
WHERE Trans_lngId IN ( 20 ,21 ,22 ) ;
But it throws error as Error Code: 1172. Result consisted of more than one row
How to translate that query. I am new to database.
Please help me in figuring out this.
UPDATE :
The way i found out was assigning into a cursor and loop through and concatenate it.
But is that the only way ? or any better way is available ?
SELECT group_concat(ManualRefund_strReasonCode SEPARATOR '|')
FROM tblManualRefunds
WHERE manualRefund_lngId in (20,21,22)
SQL Fiddle
As per xQbert Comment i tried this
SELECT
GROUP_CONCAT(COALESCE(CONCAT('shan', '|'), '') , ( ManualRefund_lngId))
INTO
#v_strManualRefundIdList
FROM tblManualRefunds ;
Its working fine.
Thanks Man.. !!!