如果数据不同,则交替编号行
Alternate Numbering rows if the data is the different
当前数据:
|LotNumber |ItemNumber |ItemName
|76 |1 |WidgetRight
|76 |1 |WidgetLeft
|76 |2 |WidgetRight
|76 |2 |WidgetLeft
|76 |7 |WidgetRight
|76 |7 |WidgetLeft
|76 |9 |WidgetRight
|76 |10 |WidgetRight
|76 |10 |WidgetLeft
|80 |3 |WidgetRight
|80 |3 |WidgetLeft
|80 |7 |WidgetRight
|80 |7 |WidgetLeft
|80 |11 |WidgetRight
|80 |31 |WidgetRight
每次 ItemNumber 更改时都需要添加一个在 1 和 2 之间交替的列
|LotNumber |ItemNumber |ItemName |NewField
|76 |1 |WidgetRight |1
|76 |1 |WidgetLeft |1
|76 |2 |WidgetRight |2
|76 |2 |WidgetLeft |2
|76 |7 |WidgetRight |1
|76 |7 |WidgetLeft |1
|76 |9 |WidgetRight |2
|76 |10 |WidgetRight |1
|76 |10 |WidgetLeft |1
|80 |3 |WidgetRight |2
|80 |3 |WidgetLeft |2
|80 |7 |WidgetRight |1
|80 |7 |WidgetLeft |1
|80 |11 |WidgetRight |2
|80 |31 |WidgetRight |1
当前代码无效...
DECLARE @LastLine Varchar(1)
SELECT ItemNumber, ItemName,
CASE WHEN ItemNumber <> LAG (ItemNumber, 1, 0) OVER (PARTITION BY LotNumber ORDER BY LotNumber, ItemNumber )
THEN
CASE WHEN @LastLine = '1'
THEN '2'
ELSE '1'
END
END AS LastLine
感谢您的帮助。
您可以只使用 dense_rank()
和算术:
select t.*,
1 + (dense_rank() over(order by lotnumber, itemnumber) + 1) % 2 as newfield
from mytable t
当前数据:
|LotNumber |ItemNumber |ItemName
|76 |1 |WidgetRight
|76 |1 |WidgetLeft
|76 |2 |WidgetRight
|76 |2 |WidgetLeft
|76 |7 |WidgetRight
|76 |7 |WidgetLeft
|76 |9 |WidgetRight
|76 |10 |WidgetRight
|76 |10 |WidgetLeft
|80 |3 |WidgetRight
|80 |3 |WidgetLeft
|80 |7 |WidgetRight
|80 |7 |WidgetLeft
|80 |11 |WidgetRight
|80 |31 |WidgetRight
每次 ItemNumber 更改时都需要添加一个在 1 和 2 之间交替的列
|LotNumber |ItemNumber |ItemName |NewField
|76 |1 |WidgetRight |1
|76 |1 |WidgetLeft |1
|76 |2 |WidgetRight |2
|76 |2 |WidgetLeft |2
|76 |7 |WidgetRight |1
|76 |7 |WidgetLeft |1
|76 |9 |WidgetRight |2
|76 |10 |WidgetRight |1
|76 |10 |WidgetLeft |1
|80 |3 |WidgetRight |2
|80 |3 |WidgetLeft |2
|80 |7 |WidgetRight |1
|80 |7 |WidgetLeft |1
|80 |11 |WidgetRight |2
|80 |31 |WidgetRight |1
当前代码无效...
DECLARE @LastLine Varchar(1)
SELECT ItemNumber, ItemName,
CASE WHEN ItemNumber <> LAG (ItemNumber, 1, 0) OVER (PARTITION BY LotNumber ORDER BY LotNumber, ItemNumber )
THEN
CASE WHEN @LastLine = '1'
THEN '2'
ELSE '1'
END
END AS LastLine
感谢您的帮助。
您可以只使用 dense_rank()
和算术:
select t.*,
1 + (dense_rank() over(order by lotnumber, itemnumber) + 1) % 2 as newfield
from mytable t