# SQL code questions

**URL:** <https://forum.inductiveautomation.com/t/sql-code-questions/893>\
**Category:** Archived Topics\
**Created:** [December 13, 2008, 7:27pm UTC](https://forum.inductiveautomation.com/t/sql-code-questions/893 "2008-12-13T19:27:36Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mrtweaver](https://avatars.discourse-cdn.com/v4/letter/m/77aa72/32.png) [@mrtweaver](https://forum.inductiveautomation.com/u/mrtweaver)\
**Post date:** [December 13, 2008, 7:27pm UTC](https://forum.inductiveautomation.com/t/sql-code-questions/893/1 "2008-12-13T19:27:36Z")

</div>

I have a query with the following code:

`SELECT TOP (100) PERCENT machine, SUM(CASE WHEN lunch = 1 THEN (runtime) END) AS lunch_time, SUM(CASE WHEN paperwrk = 1 THEN (runtime) END) 
                      AS paper_work, SUM(CASE WHEN stpbar = 0 AND lunch = 0 AND paperwrk = 0 THEN (runtime) END) AS idle_time, SUM(runtime) AS totaltime, shift, 
                      jobtask
FROM dbo.Prodtrack
GROUP BY machine, shift, jobtask
ORDER BY machine
`

What I am trying to add in is the T\_STAMP from Prodtrack table. But when I add it in it wants to make it part of the GROUP BY statement as well and it messes up the output from the query. I have tried not having in the GROUP BY but when I do this, it comes up with the error about not being aggrigate or in group by. I have tried without success MIN and MAX but they dont seem to pick up the correct information. Is there a command I am not familiar with that would allow me to do as I require?

All I want it to do is add in the value from the T\_STAMP column at the end of the data provided by the GROUP BY statement. Hopefully this is clear.

Thanks and have a great day.

---

<div class="post-metadata">

**Author:** ![Carl.Gould](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/carl.gould/32/7262_2.png) [@Carl.Gould](https://forum.inductiveautomation.com/u/Carl.Gould)\
**Post date:** [December 13, 2008, 11:11pm UTC](https://forum.inductiveautomation.com/t/sql-code-questions/893/2 "2008-12-13T23:11:55Z")

</div>

Well, when you’re grouping, each unique group becomes 1 row in the output. So, you have to perform some aggregate expression on the t\_stamp, otherwise it wouldn’t know which value of t\_stamp from the group’s rows to use. What t\_stamp do you want it to use? You could use MIN(T\_STAMP) for the first timestamp in the group, or MAX(T\_STAMP) for the last…
