3

I'm using PostgreSQL. I have a reading value in my table. From that, I have to find the consumption by subtracting previous value.

I found the SQL query. How to use that in sequelize? Is there any other option except raw queries?

SQL Query:

SELECT "readingValue",
       "readingValue" - COALESCE(LAG("readingValue") OVER
           (ORDER BY "readingTime")) AS consumption
FROM public."tableName" LIMIT 100;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
Jegan
  • 530
  • 7
  • 27

3 Answers3

3

You can do that with sequelize literal.

model.update({'count': sequelize.literal('count + 1')}, { where: { id: 1 }})

You can also do it with increment method.

Model.increment('seq', { by: 5, where: { id: 'model_id' });

Siddharth Sunchu
  • 866
  • 10
  • 13
0

I don't know if this would help, but you could also avoid using LAG and instead use a correlated subquery to find the lag value:

SELECT
    readingValue,
    readingValue - (SELECT t2.readingValue FROM public."tableName" t2
                    WHERE t2.readingValue < t1.readingValue
                    ORDER BY t2.readingValue DESC LIMIT 1) AS consumption
FROM public."tableName" t1;

Maybe this would be easier to phrase using your JavaScript ORM framework.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

We can use sequelize.literal for a field in attributes.

model.findAll({
        where: whereConditionObj,
        attributes: ['id','readingValue',
            [
                db.sequelize.literal('"readingValue" - COALESCE(LAG("readingValue") OVER (ORDER BY "readingTime"))'), 'Consumption'
            ]
        ],
        order: [['readingTime', 'ASC']],
        group:['id', 'readingValue']
    })
Jegan
  • 530
  • 7
  • 27