Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
INNER JOIN with MAX MIN
Message
From
03/09/2021 01:10:20
 
 
To
02/09/2021 18:03:12
General information
Forum:
Microsoft SQL Server
Category:
Other
Miscellaneous
Thread ID:
01682244
Message ID:
01682249
Views:
49
>I have a SQL command which has a lot of INNER JOINs. From a master table having 20 records, I need to create a report with several fields. One of the INNER JOINs has several matching records. I need to obtain the related MIN(ID) and the MAX(NoStatus) in the master report. Basically, if the INNER JOIN has 7 possibilities, I need the ID of the first record and the status of the last record. What would be the simplest way to achieve that?

Update:
I had to fiddle somewhat, but I could imagine this would be working:

WITH ranked_status AS (
SELECT Orders.Id, Orders.KdNr, Orders.Status, ROW_NUMBER() OVER (PARTITION BY KdNr ORDER BY id DESC) AS row_number
FROM Orders AS m
)
SELECT Auftrag.KdNr, Min_Id.Id, Max_Status.Status
FROM Auftrag
JOIN (SELECT MIN(Id) AS Id, KdNr FROM Orders GROUP BY KdNr) Min_Id ON Min_Id.KdNr = Auftrag.KdNr
JOIN (SELECT Status, KdNr FROM ranked_status WHERE row_number = 1) Max_Status ON Max_Status.KdNr = Auftrag.KdNr
Christian Isberner
Software Consultant
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform