简体   繁体   English

如何将 row_number 分配给 SQL 中的缺失值

[英]How to assign row_number to missing values in SQL

I want to assign row_number() to missing values as well.我也想将 row_number() 分配给缺失值。 I know that row_number will assign sequence to the non-missing values.我知道 row_number 会将序列分配给非缺失值。 How can we approach this problem?我们如何解决这个问题?

Code Snippet代码片段

SELECT id, date,sum(purchase) as purch, 
row_number() over(partition by id order by date desc) as rown 
FROM table 
where
date in (current_date(),current_date()-1,current_date()-2)
OR
date between current_date()-364 and current_date()-365
group by id,date
order by date desc

I want to use the values of sum(purchase) for particular dates, so, I want the row_number for each dates even no purchase has happened at that particular day(value could get replace with NULL).我想对特定日期使用 sum(purchase) 的值,因此,我想要每个日期的 row_number,即使在该特定日期没有发生购买(值可以用 NULL 替换)。

output should look like- output 应该看起来像 -

row_number       purchase       date
  1               23         current_date
  2               24         current_date-1
  3               null       current_date-2(let's say this is our missing date data)
  4               23         current_date-364
  5               null       current_date-365(let's say this date is mising in our data)

You first generate a list of dates then left join it with your table.您首先生成一个日期列表,然后将其与您的表连接起来。

WITH daterange AS (
  SELECT date
  FROM UNNEST(
      GENERATE_DATE_ARRAY(DATE('2021-01-01'), CURRENT_DATE(), INTERVAL 1 DAY)
  )   AS date
),  
yourtable AS (
  SELECT DATE'2022-09-15' AS date, 23 AS purchase UNION ALL
  SELECT DATE'2022-09-14' AS date, 24 AS purchase UNION ALL
  SELECT DATE'2021-09-16' AS date, 23 AS purchase
)

SELECT 
  ROW_NUMBER() OVER(ORDER BY t1.date DESC) AS row_number, 
  t2.purchase, 
  t1.date
FROM daterange t1
LEFT JOIN yourtable t2 ON t1.date = t2.date
WHERE t1.date IN (current_date(), current_date()-1, current_date()-2)
OR (t1.date BETWEEN current_date()-365 AND current_date()-364)

Query Results:查询结果:

row_number  purchase    date
1           23          2022-09-15
2           24          2022-09-14
3           null        2022-09-13
4           23          2021-09-16
5           null        2021-09-15

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM