# SQL Query from Expression

**URL:** <https://forum.inductiveautomation.com/t/sql-query-from-expression/1764>\
**Category:** Archived Topics\
**Created:** [April 16, 2010, 5:29pm UTC](https://forum.inductiveautomation.com/t/sql-query-from-expression/1764 "2010-04-16T17:29:56Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bhastie](https://avatars.discourse-cdn.com/v4/letter/b/d6d6ee/32.png) [@bhastie](https://forum.inductiveautomation.com/u/bhastie)\
**Post date:** [April 16, 2010, 5:29pm UTC](https://forum.inductiveautomation.com/t/sql-query-from-expression/1764/1 "2010-04-16T17:29:56Z")

</div>

I have a SQL query to calculate the production rate of a machine based on the count now and the count an hour ago. The trouble is that it errors out if there is now data or if the query returns a divide by zero. I need to encapsulate the query within an expression or script to test the values ahead of time or provide a failover. The query is as follows:

`Select CAST((max(Count)-min(Count)) / (DatePart(mi,max(t_stamp) - min(t_stamp))) AS DECIMAL(5,2)) as "BPM"
FROM Case_Inkjets
WHERE EquipID = {Root Container.P0248.EquipID} and 
t_stamp > DateAdd(hh,-1,GetDate()) and
Count > 0`

What do you suggest?

---

<div class="post-metadata">

**Author:** ![Travis.Cox](https://avatars.discourse-cdn.com/v4/letter/t/b9bd4f/32.png) [@Travis.Cox](https://forum.inductiveautomation.com/u/Travis.Cox)\
**Post date:** [April 16, 2010, 6:31pm UTC](https://forum.inductiveautomation.com/t/sql-query-from-expression/1764/2 "2010-04-16T18:31:22Z")

</div>

To add more logic into the query:

`Select COALESCE(CAST(CASE WHEN (DatePart(mi,max(t_stamp) - min(t_stamp))) <= 0 THEN 0 ELSE (max(Count)-min(Count)) / (DatePart(mi,max(t_stamp) - min(t_stamp))) END AS DECIMAL(5,2)),0) as "BPM"
FROM Case_Inkjets
WHERE EquipID = {Root Container.P0248.EquipID} and
t_stamp > DateAdd(hh,-1,GetDate()) and
Count > 0`  
Try this out, it detects when you divide by zero and if no rows exist it can coalesce the value to 0.

---

<div class="post-metadata">

**Author:** ![bhastie](https://avatars.discourse-cdn.com/v4/letter/b/d6d6ee/32.png) [@bhastie](https://forum.inductiveautomation.com/u/bhastie)\
**Post date:** [April 16, 2010, 8:40pm UTC](https://forum.inductiveautomation.com/t/sql-query-from-expression/1764/3 "2010-04-16T20:40:50Z")

</div>

That did the trick, thanks! 😃
