提取最新的非零收入行
extract the latest non zero revenue row
示例数据:
输入:
product_name| snapshot_time (varchar)| revenue (varchar) |
product_A | 2021-07-01 | [=10=].0 |
product_A | 2021-04-01 | .12 |
product_A | 2021-06-01 | .23 |
product_B | ...... | ...... |
product_C | ...... | ....... |
......
输出应该是:
product_name| snapshot_time (varchar)| revenue (varchar) |
product_A | 2021-06-01 | .23 |
product_B | lastest time | non zero value |
product_C | lastest time |non zero value |
......
要求是:
对于每个产品:
- 如果有任何非零收入记录:
提取最新的非零收入行
- 如果所有记录都是
[=13=].0
:
提取最新的[=13=].0
收入行
我试过了:
with t as (
select *, row_number() over(partition by product_name order by snapshot_time desc, revenue desc) as rnk
from sample_data)
SELECT product_name, snapshot_time, revenue
FROM t where rnk = 1;
但这是错误的,因为它可能会提取 [=13=].0
行。
考虑这个版本:
WITH t AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY product_name
ORDER BY revenue > 0 DESC, snapshot_time DESC) rn
FROM sample_data
)
SELECT product_name, snapshot_time, revenue
FROM t
WHERE rn = 1;
示例数据:
输入:
product_name| snapshot_time (varchar)| revenue (varchar) |
product_A | 2021-07-01 | [=10=].0 |
product_A | 2021-04-01 | .12 |
product_A | 2021-06-01 | .23 |
product_B | ...... | ...... |
product_C | ...... | ....... |
......
输出应该是:
product_name| snapshot_time (varchar)| revenue (varchar) |
product_A | 2021-06-01 | .23 |
product_B | lastest time | non zero value |
product_C | lastest time |non zero value |
......
要求是:
对于每个产品:
- 如果有任何非零收入记录:
提取最新的非零收入行
- 如果所有记录都是
[=13=].0
:
提取最新的[=13=].0
收入行
我试过了:
with t as (
select *, row_number() over(partition by product_name order by snapshot_time desc, revenue desc) as rnk
from sample_data)
SELECT product_name, snapshot_time, revenue
FROM t where rnk = 1;
但这是错误的,因为它可能会提取 [=13=].0
行。
考虑这个版本:
WITH t AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY product_name
ORDER BY revenue > 0 DESC, snapshot_time DESC) rn
FROM sample_data
)
SELECT product_name, snapshot_time, revenue
FROM t
WHERE rn = 1;