简体   繁体   中英

RowNumber on join?

    TableBoxes                          TableItems
 BoxCode    BoxDesc                   ItemNo    BoxCode       ItemDesc
    X1        Freight1                   123       X1            Tomatoes
    X4        Freight2                   124       X1            Apples  
    X8        Freight3                   128       X4            Potatoes   

I want result row for BoxCode=X1 only, with output ordered by ItemNo

BoxNumber         ItemNo               ItemDesc
   1                1                     Tomatoes
   1                2                     Apples

I can easily get the 'ItemNo' serial working by using row_number() on ItemNo. How do I find the serial of the box from the first table ? My current query

select 
    row_number() over(
          order by a.ItemNo
    )as ItemNo
    ,ItemDesc
from 
    TableItems a 
    inner join TableBoxes b 
        on a.BoxCode=b.BoxCode 
where
    a.BoxCode='X1'

Can't figure out how to select serial for BoxCode, Damien.

Is this what you want?

WITH TableBoxesRanked AS (
  SELECT
    *,
    BoxNumber = ROW_NUMBER() OVER (ORDER BY BoxCode)
  FROM TableBoxes
)
SELECT
  b.BoxNumber,
  ItemNumber = ROW_NUMBER() OVER (ORDER BY i.ItemNo),
  i.ItemDesc
FROM TableItems i
  INNER JOIN TableBoxesRanked b ON i.BoxCode = b.BoxCode
WHERE a.BoxCode = 'X1'

Use dense_rank() like the below :

SELECT DENSE_RANK() OVER(order by a.BoxCode) , row_number() over(order by a.ItemNo)as ItemNo, ItemDesc 
from #TableItems a 
inner join #TableBoxes b on a.BoxCode=b.BoxCode where a.BoxCode in ('X1','X4')

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