TableBoxes TableItems
BoxCode BoxDesc ItemNo BoxCode ItemDesc
X1 Freight1 123 X1 Tomatoes
X4 Freight2 124 X1 Apples
X8 Freight3 128 X4 Potatoes
我想要BoxCode = X1的结果行,输出按ItemNo
排序BoxNumber ItemNo ItemDesc
1 1 Tomatoes
1 2 Apples
我可以通过在ItemNo上使用 row_number()轻松获得'ItemNo'序列。如何从第一张表中找到盒子的序列? 我当前的查询
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'
无法弄清楚如何为BoxCode,Damien选择序列。
答案 0 :(得分:2)
这是你想要的吗?
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'
答案 1 :(得分:1)
使用如下所示的dense_rank():
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')