简体   繁体   中英

SQL select the max value, associate at specific range date field

I should select the purchase cost on a invoice table by comparing the date of sale example

the invoice table (about 20000 row)

| num. | cod_art | date |
---------------------
|   1  |  OROK3  | 22/12/2013 |
|   1  |  PIZZ4  | 22/12/2013 |
|   1  |  MYGO5  | 22/12/2013 |
|   2  |  CAND4  | 27/12/2013 |
|   2  |  OROK3  | 27/12/2013 |
|   2  |  SAGA8  | 27/12/2013 |
|   3  |  PIZZ4  | 30/12/2013 |
|   4  |  CAND4  | 30/12/2013 |

table of costs per item (about 4000 row)

| cod_art |  cost  | purchase dt.|
---------------------
|  OROK3  | 11.23  |  15/12/2013 |
|  OROK3  | 10.55  |  17/12/2013 |
|  OROK3  | 12.00  |  24/12/2013 |
|  OROK3  | 11.50  |  30/12/2013 |
|  PIZZ4  |  2.56  |  10/12/2013 |
|  PIZZ4  |  3.00  |  24/12/2013 |
|  SAGA8  | 23.45  |  25/12/2013 |
|  CAND4  |  1.33  |  31/12/2013 |

expected result

| num. | cod_art |    date    ||  cost  | purchase dt.|
---------------------
|   1  |  OROK3  | 22/12/2013 || 10.55  |  17/12/2013 |
|   1  |  PIZZ4  | 22/12/2013 ||  2.56  |  10/12/2013 |
|   1  |  MYGO5  | 22/12/2013 ||  null  |     null    |
|   2  |  CAND4  | 27/12/2013 ||  null  |     null    |
|   2  |  OROK3  | 27/12/2013 || 12.00  |  24/12/2013 |
|   2  |  SAGA8  | 27/12/2013 || 23.45  |  25/12/2013 |
|   3  |  PIZZ4  | 30/12/2013 ||  3.00  |  24/12/2013 |
|   4  |  CAND4  | 30/12/2013 ||  null  |     null    |

is it a possibile solution?

    SELECT * 
    FROM (  SELECT 
                *,
                dense_rank() over(PARTITION BY idfat,art order by data_purch desc) rn 
            FROM (  SELECT  
                        i.idfat,i.art,i.data_sale,p.data_purch,p.PRZ 
                    FROM @Invoice i 
                        left join @Purchase p on i.art=p.art 
                    WHERE 
                        data_sale>data_purch
                ) t
        ) src 
    WHERE 
        rn = 1

what is best solution?

If item have not purchased more that one time in single day then following query might help you to achieve your result.

SELECT I.idfat, I.art, I.Data_Sale, P.Data_Sale, p.PRZ 
FROM Invoice As I
LEFT JOIN Purchase As P On P.art = I.art
    AND P.data_purch =
        (SELECT TOP 1 PA.data_purch
         FROM Purchase As PA
         WHERE PA.art = I.art
           AND PA.data_purch <= I.Data_Sale
         ORDER BY PA.data_purch Desc
        )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM