我正在尝试以下列格式在表格中插入记录
Name Amount Date Counter
A 100 Jan 1 1
A 100 Jan2 1
A 200 Jan 10 2
A 300 Mar 30 3
B 50 Jan 7 1
C 20 Jan 7 1
有人能告诉我用于为Counter字段生成值的sql。 每当金额改变时,计数器值应递增,并在名称改变时重置。
答案 0 :(得分:2)
您需要的是DENSE_RANK功能。不幸的是,它不是在TD14.10之前原生实现的,但它可以使用嵌套的OLAP函数编写:
SELECT
Name
,Amount
,date_col
,SUM(flag)
OVER (PARTITION BY Name
ORDER BY date_col
ROWS UNBOUNDED PRECEDING) AS "DENSE_RANK"
FROM
(
SELECT
Name
,Amount
,date_col
,CASE
WHEN Amount = MIN(Amount)
OVER (PARTITION BY Name
ORDER BY date_col
ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING)
THEN 0
ELSE 1
END AS flag
FROM dropme
) AS dt;