Question

I have a database table that stores data to show on a report. Each time records are inserted into the database, another row is added except the ReportNumber row is incremented. I've been searching and can't seem to find anyone else who may have asked this. I need the stored procedure to get the latest report info (highest number in the ReportNumber row). How can I do this? Here's an example.

Year     Data     ReportNumber
2014     135      1
2014     135      2
2014     136      1
2014     136      2

When I run the report I only want to show the latest data based on the ReportNumber (2 in this case)

Was it helpful?

Solution

Does this do it:

select * 
  from Table
 where ReportNumber in (select max(ReportNumber) 
                          from Table)

OTHER TIPS

Why not use order by like

select * from 
report_table
order by
ReportNumber desc 

(OR)

select * from 
report_table
where ReportNumber = (select max(ReportNumber) from report_table)

Assuming I'm understanding your question correctly, you want to select the row which has the max reportnumber grouped by year and data? If so, there are a number of ways. Here is one using the row_number():

with cte as (
    select t.year, 
        t.data, 
         t.reportnumber, 
         row_number() over (partition by year, data order by reportnumber desc) rn
    from yourtable t
)
select *
from cte
where rn = 1

If you want to get ALL rows where ReportNumber is equal to the maximum value in your table :

SELECT yourTable.*
FROM yourTable
CROSS JOIN (SELECT Max(reportNumber) as maxRep)
WHERE yourTable.ReportNumber = maxRep

If you want, for each value of data, to get the latest report :

SELECT yourTable.*
FROM yourTable
CROSS JOIN (
    SELECT Data, Max(reportNumber) as maxRep 
    FROM yourTable 
    GROUP BY Data) as maxTable
ON yourTable.ReportNumber = MaxTable.maxRep
    AND yourTable.Data = MaxTable.Data

If you are using SQL Server 2005 or later, you can also use TOP in combination with the WITH TIES option. This selects all records having the same (maximum, because of the ordering) ReportNumber.

SELECT TOP 1 WITH TIES *
FROM MyTable
ORDER BY ReportNumber DESC
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top