0

I have data like below : Draw data

Target to show in clients : Show data

My SQL like below :

SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'ifnull(SUM(case when itemname = ''',
      itemname,
      ''' then itemvalue end),0) AS `',
      itemname, '`'
    )
  ) INTO @sql
FROM
  history;
SET @sql = CONCAT('SELECT hostid, ', @sql, ' 
                  FROM history 
                   GROUP BY hostid');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt

Above coding can running on Toad and return to data but when I applied to query of Nodejs It stopped in INTO @sql

Please help me if you have any solution .

Thanks

Data table :

DROP TABLE IF EXISTS history;
CREATE TABLE history
(hostid INT,
itemname VARCHAR(5),
itemvalue INT);

INSERT INTO history VALUES(1,'A',10),(1,'B',3),(2,'A',9),
(2,'C',40),(2,'D',5),
(3,'A',14),(3,'B',67),(3,'D',8);

Nodejs module

const sql = require('../config/db')

exports.getreportsheet = (req, res) => {
  let sqlstring = `SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'ifnull(SUM(case when itemname = ''',
      itemname,
      ''' then itemvalue end),0) AS `',
      itemname, '`'
    )
  ) INTO @sql
FROM
  history;
SET @sql = CONCAT('SELECT hostid, ', @sql, ' 
                  FROM history 
                   GROUP BY hostid');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt `
sql.query(sqlstring,
        ['Page', 20],
        function (err, results) {
            console.log('Loading data', results, sqlstring);
            return res.status(200).json({
                data: results
            })
        }
    );
};
  • Would be a good idea to share your code which shows how you run that sql from Node – kRiZ Jan 03 '23 at 04:06
  • Sure, I did post Nodejs – user8630615 Jan 03 '23 at 12:39
  • 1
    Add your queries as a procedure then call it – SelVazi Jan 03 '23 at 12:43
  • This Could help you : https://stackoverflow.com/questions/23266854/node-mysql-multiple-statements-in-one-query – SelVazi Jan 03 '23 at 14:54
  • @SelVazi Thank you so much . I have changed the parameters connection multipleStatements: true, . It is working for multiple block but return is not Data. – user8630615 Jan 03 '23 at 15:50
  • Why are you using one SQL query to build and execute another SQL query? Why can't you directly run the query which you are building in sql from Node? – kRiZ Jan 04 '23 at 00:11
  • @kRiZ Q1 : Because the itemname is not fixed so it is not available to use CASE WHEN . Q2 : Direct to run for developer but for end user we need to publish to WEB. thanks. – user8630615 Jan 04 '23 at 03:10

0 Answers0