{"id":1471,"date":"2019-02-23T12:00:35","date_gmt":"2019-02-23T04:00:35","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=1471"},"modified":"2020-05-12T10:26:13","modified_gmt":"2020-05-12T02:26:13","slug":"sql-statement-for-selecting-the-latest-record-in-each-group","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/sql-statement-for-selecting-the-latest-record-in-each-group\/","title":{"rendered":"SQL statement for selecting the latest record in each group"},"content":{"rendered":"<p>When you have multiple <a href=\"https:\/\/www.techcoil.com\/glossary\/internet-of-things\" rel=\"noopener\" target=\"_blank\">IoT<\/a> devices of the same type, you may collect data in a single database table.<\/p>\n<p>In such a case, you may choose to group data based on the device ID.<\/p>\n<p>So how do you display the latest data capture from each device?<\/p>\n<p>In this situation, we can choose to run an SQL statement that will return the latest record in each group.<\/p>\n<h2>A sample scenario that requires an SQL statement for selecting the latest record in each group<\/h2>\n<p>For the purpose of this post, assume that we have deployed multiple <a href=\"https:\/\/www.techcoil.com\/blog\/tag\/raspberry-pi\/\" target=\"_blank\" rel=\"noopener\">Raspberry Pis<\/a> to capture temperature and humidity in different locations. After a <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-read-temperature-and-humidity-from-a-dht11-sensor-that-is-connected-to-a-raspberry-pi-3\/\" rel=\"noopener\" target=\"_blank\">Raspberry Pi reads temperature and humidity from a DHT11 sensor<\/a>, it sends them to a <a href=\"https:\/\/www.techcoil.com\/glossary\/http-server\/\" rel=\"noopener\" target=\"_blank\">HTTP server<\/a> endpoint. <\/p>\n<p>When the endpoint receives the data, it saves the data into an SQL database with the following schema:<br \/>\n<code>DEVICE_DATA(ID, DEVICE_ID, HUMIDITY, TEMPERATURE, TIMESTAMP_UNIX_EPOCH)<\/code><\/p>\n<p>In addition to capturing data, there is also another endpoint returns the most recent temperature and humidity reading captured by each of the Raspberry Pi.<\/p>\n<p>Given that, <strong>we choose to run an SQL statement that will return the latest record in each group; with the device ID serving as the group number<\/strong>.<\/p>\n<h2>Constructing the SQL statement for selecting the latest record in each group<\/h2>\n<p>In order to get the SQL statement for selecting the latest record in each group, we first need a query to get the latest timestamp:<\/p>\n<pre class=\"brush: sql; title: ; notranslate\" title=\"\">\r\nSELECT DEVICE_ID, max(TIMESTAMP_UNIX_EPOCH) as MaxTime\r\nFROM DEVICE_DATA\r\nGROUP BY DEVICE_ID\r\n<\/pre>\n<p>After the above statement is executed, we get a table of unique device id alongside the maximum timestamp in the group.<\/p>\n<p>However, this statement does not give the temperature and humidity readings that we will need for our endpoint. Therefore, we need to use a inner join statement to join the results with the original device table:<\/p>\n<pre class=\"brush: sql; title: ; notranslate\" title=\"\">\r\nSELECT dd.DEVICE_ID, dd.HUMIDITY, dd.TEMPERATURE, dd.TIMESTAMP_UNIX_EPOCH\r\nFROM \r\n(SELECT DEVICE_ID, max(TIMESTAMP_UNIX_EPOCH) as MaxTime \r\nFROM DEVICE_DATA \r\nGROUP BY DEVICE_ID) r\r\nINNER JOIN DEVICE_DATA dd\r\nON dd.DEVICE_ID = r.DEVICE_ID AND dd.TIMESTAMP_UNIX_EPOCH = r.MaxTime\r\n<\/pre>\n<p>By joining the result from the previous SQL statement, we will be able to augment the results with the most recent temperature and humidity reading that each Raspberry Pi had captured.<\/p>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-nJ\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-nJ&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-nJ&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F1471&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>When you have multiple <a href=\"https:\/\/www.techcoil.com\/glossary\/internet-of-things\" rel=\"noopener\" target=\"_blank\">IoT<\/a> devices of the same type, you may collect data in a single database table.<\/p>\n<p>In such a case, you may choose to group data based on the device ID.<\/p>\n<p>So how do you display the latest data capture from each device?<\/p>\n<p>In this situation, we can choose to run an SQL statement that will return the latest record in each group.<\/p>\n","protected":false},"author":1,"featured_media":1472,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[602,600,603,26,601],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/sql-logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-nJ","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/1471"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=1471"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/1471\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1472"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=1471"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=1471"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=1471"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}