I have a very similar question to what was asked here for an Oracle DB (but I have an SQL Server 2012). The example I have used as a starter is based on the answer given here.
What I have is these four columns:
[L2] ,[DateofReporting],[L3]
and [ServerName]
more or less at a random day data is added to that table, but if it is, it will always be the same [L2],[DateofReporting]
,[L3]
but with a different [ServerName]
Now I want to extract that data to give me all the servers [ServerName]
, which were added last for all months and years grouped by L2
, L3
and the related month and year (coming from [DateofReporting]
) .
SELECT [ID],[L2],[DateofReporting],[L3],[ServerName]
FROM (
select *,
max([DateofReporting])
OVER (PARTITION BY YEAR([DateofReporting]),
Month([DateofReporting])) maxdate
from [EADATAGOV].[Governance].[ToDos]
)max_date
where [DateofReporting] = maxdate
The problem I am phasing is, that the data is incomplete and their is obviously a bug in my statement. By now I don't see the tree for the forest, could you please help me clean up that SQL statement, or if there is a smarter way of doing it, I am open to suggestions.
I was thinking about utilizing ROW_NUMBER()
to mark the relevant entries and than do a select on them, but I have never worked with that before.
thx Jan
example of output:
ID L2 DateofReporting L3 name
18214 Summer 2017-09-20 cloud BINHAS01105 <--
18215 Summer 2017-09-20 lightbulb BINHAS60276 <--
18217 Summer 2017-09-20 lightbulb CNAHAS62003 <--
15297 Summer 2017-09-15 cloud CINHAS01105
15298 Summer 2017-09-15 boat CINHAS60277
15300 Summer 2017-09-15 lightbulb DNAHAS62003
10512 Summer 2017-08-20 lightbulb DNAHAS62003 <--
the ones pointed out, are the ones I would expect to see in the result. As eg. boat does not have a newer entry than that of the 09-15.
new approach:
Select [L2],
MAX([DateofReporting]) LDateOfTest
from [EADATAGOV].[Governance].[ToDos]
group by [L2], YEAR([DateofReporting]), Month([DateofReporting]) ,[DType]
having DType= 'test'
order by LDateOfTest desc, L2 desc
This provides me (correctly) the latest date for each L2 for every month. Now in theory I should be able to use another query on the very same table where L2 and the LDateOfTest match. My idea of a subselect does not work, as I can only pass one criteria, not two. But I don't know how that works, can you help me with the join(?) ?