有没有办法创建一个具有运行数的列,只要另一列中的值具有特定值,该列就会将其值增加1?例如,如果我们有
colA
a
c
change
b
c
b
change
b
a
.
.
.
然后我想
colA colB
a 1
c 1
change 2
b 2
c 2
b 2
change 3
b 3
a 3
. .
. .
. .
答案 0 :(得分:4)
您尚未指定订购方式,因此我将使用idColumn
:
SELECT colA,
colB = (SELECT COUNT(*) FROM dbo.TableName t2
WHERE colA = 'change'
AND t2.idColumn <= t.idColumn) + 1
FROM dbo.TableName t
ORDER BY idColumn
答案 1 :(得分:4)
以下所有解决方案都假设您有一些明确的orderCriteria
,您可以通过它来订购活动。
SELECT
colA,
COUNT(*) FILTER (WHERE colA = 'change') OVER (ORDER BY orderCriteria) + 1 colB,
FROM my_table
ORDER BY orderCriteria
(包括CUBRID,DB2,Firebird 3,HANA,Informix,Oracle,PostgreSQL,Redshift,SQL Server,Sybase SQL Anywhere等)
SELECT
colA,
COUNT(CASE WHEN colA = 'change' THEN 1 END) OVER (ORDER BY orderCriteria) + 1 colB,
FROM my_table
ORDER BY orderCriteria
SELECT
colA,
(SELECT COUNT(*)
FROM my_table t2
WHERE t2.orderCriteria <= t1.orderCriteria
AND t2.colA = 'change') + 1 colB
FROM my_table t1
ORDER BY orderCriteria