Let's say I have this (SQL server) database, sorted by value A and value B should be incremented only when the value A gets change:
BillNo Value B
SC-P1100 1
SC-P1100 1 BillNo changes
SC-blb00 2 BillNo changes
SC-P6010 3
SC-P6010 3
SC-P6010 3 BillNo changes
SB-T1810 4
How do I select the rows in the above manner? Please answer
Thanks
You can do it like this
UPDATE tableA
SET BillNo='new value'
, ValueB=ValueB+1
WHERE BillNo='Old value';
You can use CTE to do that.
WITH CTE (Col1, RowNumber)
AS
(
SELECT <YOUR_COLUMN_NAME_HERE> AS Col1, ROW_NUMBER() OVER (ORDER BY Col1) As RowNumber
FROM <YOUR_TABLE_NAME_HERE>
)
SELECT Col1,
(
SELECT COUNT(DISTINCT Col1)
FROM CTE InnerCTE
WHERE InnerCTE.RowNumber <= OuterCTE.RowNumber
) As NumberOfDistinctItemsInCol1
FROM CTE OuterCTE
Be sure to replace <YOUR_COLUMN_NAME_HERE> with your actual column name and <YOUR_TABLE_NAME_HERE> with your actual table name.
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.