Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL selecting rows by most recent date with two unique columns

Tags:

sql

oracle

Using the following query and results, I'm looking for the most recent entry where the ChargeId and ChargeType are unique.

select chargeId, chargeType, serviceMonth from invoice      CHARGEID    CHARGETYPE  SERVICEMONTH 1   101         R           8/1/2008 2   161         N           2/1/2008 3   101         R           2/1/2008 4   101         R           3/1/2008 5   101         R           4/1/2008 6   101         R           5/1/2008 7   101         R           6/1/2008 8   101         R           7/1/2008 

Desired:

    CHARGEID    CHARGETYPE  SERVICEMONTH 1   101         R           8/1/2008 2   161         N           2/1/2008 
like image 817
jgreep Avatar asked Oct 09 '08 21:10

jgreep


People also ask

How do I select the rows with the most recent date in SQL?

Here is the syntax that we can use to get the latest date records in SQL Server. Select column_name, .. From table_name Order By date_column Desc; Now, let's use the given syntax to select the last 10 records from our sample table.

How do I find unique two column combinations in SQL?

Select with distinct on all columns of the first query. Select with distinct on multiple columns and order by clause. Count() function and select with distinct on multiple columns.

How do I select the last 2 records in SQL?

To select last two rows, use ORDER BY DESC LIMIT 2.

How do I select latest timestamp in SQL?

To get the last updated record in SQL Server: We can write trigger (which automatically fires) i.e. whenever there is a change (update) that occurs on a row, the “lastupdatedby” column value should get updated by the current timestamp.


1 Answers

You can use a GROUP BY to group items by type and id. Then you can use the MAX() Aggregate function to get the most recent service month. The below returns a result set with ChargeId, ChargeType, and MostRecentServiceMonth

SELECT   CHARGEID,   CHARGETYPE,   MAX(SERVICEMONTH) AS "MostRecentServiceMonth" FROM INVOICE GROUP BY CHARGEID, CHARGETYPE 
like image 153
Mitchel Sellers Avatar answered Oct 12 '22 01:10

Mitchel Sellers