I'm not sure whether this is complicated or I am lost about it.
Lets take this given table orders:
| ORDERNO | ORDER_DATE | MAT1 | Menge |
| ------------ | ------------ | ------------ | ------------ |
| 3912 | 09-09-1996 00:00:00 | 1 | 1020 |
| 3039 | 17-07-1995 00:00:00 | 1 | 30000 |
| 2985 | 27-06-1995 00:00:00 | 1 | 100000 |
| 2879 | 20-04-1995 00:00:00 | 1 | 100000 |
| 2735 | 06-02-1995 00:00:00 | 1 | 100000 |
| 3000 | 29-06-1995 00:00:00 | 2 | 30000 |
| 2986 | 27-06-1995 00:00:00 | 2 | 100000 |
| 2927 | 18-05-1995 00:00:00 | 2 | 100000 |
| 2794 | 08-03-1995 00:00:00 | 2 | 100000 |
| 2738 | 07-02-1995 00:00:00 | 2 | 100000 |
| 2652 | 06-01-1995 00:00:00 | 2 | 30000 |
| 3082 | 09-08-1995 00:00:00 | 3 | 30000 |
| 2717 | 31-01-1995 00:00:00 | 3 | 30000 |
| 806 | 28-10-1991 00:00:00 | 3 | 20000 |
| 693 | 02-07-1991 00:00:00 | 3 | 15000 |
| 29008 | 13-02-2023 09:02:02 | 4 | 324000 |
| 28871 | 07-12-2022 10:27:12 | 4 | 580000 |
| 28787 | 03-11-2022 13:46:42 | 4 | 300000 |
| 28726 | 12-10-2022 09:28:18 | 4 | 580000 |
| 28676 | 07-09-2022 11:33:53 | 4 | 580000 |
| 28661 | 31-08-2022 15:26:44 | 4 | 360000 |
and a table materials
nr | price | weight |
---|---|---|
1 | 0.9797 | 0.0740 |
2 | 0.0000 | 0.0000 |
3 | 0.0919 | 0.0740 |
4 | 0.0000 | 0.0850 |
How is it possible to get the newest 3 orders for each material on a SQL Server 2017 so it would be like this:
nr | price | weight | ORDERNO | ORDER_DATE | MAT1 | Menge |
---|---|---|---|---|---|---|
1 | 0.9797 | 0.0740 | 3912 | 09-09-1996 00:00:00 | 1 | 1020 |
1 | 0.9797 | 0.0740 | 3039 | 17-07-1995 00:00:00 | 1 | 30000 |
1 | 0.9797 | 0.0740 | 2985 | 27-06-1995 00:00:00 | 1 | 100000 |
2 | 0.0000 | 0.0000 | 3000 | 29-06-1995 00:00:00 | 2 | 30000 |
2 | 0.0000 | 0.0000 | 2986 | 27-06-1995 00:00:00 | 2 | 100000 |
2 | 0.0000 | 0.0000 | 2927 | 18-05-1995 00:00:00 | 2 | 100000 |
I tried serveral variants.
What worked without a problem is displaying all orders of each material with a join or display the newest order for each material. But how to get the 3 newest orders for a material? SQL for newest order:
select
*
from
Material m
join (
select
o.ORDERNO,
max(o.ORDER_DATE) as ORDER_DATE,
o.MAT1,
o.Menge
from
orders o
group by
o.ORDERNO,
o.MAT1,
o.Menge) as t1 on
t1.MAT1 = m.NR
3条答案
按热度按时间ewm0tg9j1#
I'd use a
cross apply
for that:cross apply
allows you to filter a sub-query with values from the outer part.UPD: you're asking for 5 newest record in the description and for 3 newest in the query's text. If 5 newest records is what you need, just update the
top
part of the query.smdncfj32#
You can use WINDOW FUNCTION(ROW_NUMBER) to solve the problem
You can create insert Base data with the following statements:
kr98yfug3#
You can get a row number by mat1 entry in the orders using the row_number window function.
To extent it to your scenario, just filter by row number
Using a window function uses "query cost" than a cross apply, although the cross apply is simpler to understand