简体   繁体   中英

How to get the row record of max(date) using SQL Server?

I have two table called TableNumber and TableDetails

TableNumber

ItemID  TableDetailsID   Qty
----------------------------
111     12121             5
111     12121            20 
112     12121            10
123     12121             5

111     22121            25
111     22121            25
123     22121            2

TableDetails

ID       placed   TableDetailsNumber    Date
--------------------------------------------------
12121    London    555                  2017-05-31
22121    Dubai     556                  2017-07-31   <-- Max Date of Item 111

Expecting output

ItemID    Placed    TableDetailsNumber    Date         Qty
----------------------------------------------------------
111       Dubai     556                  2017-07-31    50    //(25 + 25) of 22121
112       London    555                  2017-05-31    10
123       Dubai     556                  2017-07-31     2

I tried to do MAX(Date), But I cannot bring the column Placed,TableDetails using Grouping

As well as I don't how to make sum the Qty of ItemID with Same TableDetailsNumber

Please give me explanation with your answer to understand , Thanks

Row_number() is a ranking window function that will assign a number that resets starting with 1 for each given set of columns in the partition by and in the order of the columns in the order by .

If we partition by ItemId and order by Date desc then the row with the latest Date for each ItemId is given the row_number() of 1 .

With that we can filter the results of the join and aggregation with either a subquery, common table expression , or with top with ties .

using top with ties and row_number() :

select top 1 with ties
    tn.ItemId
  , td.Placed 
  , td.TableDetailsNumber
  , td.Date
  , Qty = sum(tn.Qty)
from TableNumber tn
  inner join TableDetails td
    on tn.TableDetailsId = td.Id
group by
    tn.ItemId
  , td.Placed 
  , td.TableDetailsNumber
  , td.Date
order by row_number() over (partition by tn.ItemId order by td.Date desc);

or a common table expression with row_number()

;with cte as (
select 
    tn.ItemId
  , td.Placed 
  , td.TableDetailsNumber
  , td.Date
  , Qty = sum(tn.Qty)
  , rn = row_number() over (partition by tn.ItemId order by td.Date desc)
from TableNumber tn
  inner join TableDetails td
    on tn.TableDetailsId = td.Id
group by
    tn.ItemId
  , td.Placed 
  , td.TableDetailsNumber
  , td.Date
)
select ItemId, Placed, TableDetailsNumber, Date, Qty 
from cte
where rn = 1;

Another option using cross apply() :

select
    i.ItemId
  , x.Placed 
  , x.TableDetailsNumber
  , x.Date
  , x.Qty 
from (select distinct ItemId from TableNumber) i
  cross apply (
    select top 1
        tn.ItemId
      , td.Placed 
      , td.TableDetailsNumber
      , td.Date
      , Qty = sum(tn.Qty)
    from TableNumber tn
      inner join TableDetails td
        on tn.TableDetailsId = td.Id
    where tn.ItemId = i.Itemid
    group by
        tn.ItemId
      , td.Placed 
      , td.TableDetailsNumber
      , td.Date
    order by td.Date desc
    ) x

rextester demo: http://rextester.com/QNV39265

Each return:

+--------+--------+--------------------+------------+-----+
| ItemId | Placed | TableDetailsNumber |    Date    | Qty |
+--------+--------+--------------------+------------+-----+
|    111 | Dubai  |                556 | 2017-07-31 |  50 |
|    112 | London |                555 | 2017-05-31 |  10 |
|    123 | Dubai  |                556 | 2017-07-31 |   2 |
+--------+--------+--------------------+------------+-----+

This would appear to return the results that you want:

select n.itemid, d.placed, d.TableDetailsNumber, d.date, sum(n.qty)
from tablenumber n join
     tabledetails d
     on n.TableDetailsId = d.TableDetailsId
group by n.itemid, d.placed, d.TableDetailsNumber;

But this doesn't get the latest date. For that:

select nd.*
from (select n.itemid, d.placed, d.TableDetailsNumber, d.date, sum(n.qty),
             max(d.date) over (partition by n.itemid) as maxdate
      from tablenumber n join
           tabledetails d
           on n.TableDetailsId = d.TableDetailsId
      group by n.itemid, d.placed, d.TableDetailsNumber
     ) nd
where date = maxdate;

You could also do an inner join. I included all of the table creation code to replicate the test case and prove its accuracy.

Table Creation and Inserts

CREATE TABLE TableNumber (ItemID INT, TableDetailsID INT, Qty INT)
CREATE TABLE TableDetails (ID INT, placed VARCHAR(25), TableDetailsNumber INT, DetailsDate Date)


INSERT INTO TableNumber 
    values 
     (111,12121,5),
     (111,12121,20),
     (112,12121,10),
     (123,12121,5),
     (111,22121,25),
     (111,22121,25),
     (123,22121,2)

INSERT INTO TableDetails 
    values 
     (12121,'London',555,'2017-05-31'),
     (22121,'Dubai',556,'2017-07-31')

Query

SELECT
     TN.ItemID
    ,TD.Placed
    ,TD.TableDetailsNumber
    ,MaxTable.maxDate
    ,Sum(TN.Qty) 'Qty'
FROM TableNumber TN
JOIN TableDetails TD 
    on TD.ID = TN.TableDetailsID
JOIN (
        SELECT 
         ItemID
        ,max(TD.DetailsDate) maxDate
        FROM TableNumber TN
        JOIN TableDetails TD 
            on TD.ID = TN.TableDetailsID
        GROUP BY 
         ItemID
        ) as MaxTable
    on MaxTable.maxDate = TD.DetailsDate
    and MaxTable.ItemID = TN.ItemID
GROUP BY 
     tn.ItemId
  , td.Placed 
  , td.TableDetailsNumber
  , MaxTable.maxDate

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