返回介绍

solution / 2300-2399 / 2388.Change Null Values in a Table to the Previous Value / README_EN

发布于 2024-06-17 01:03:06 字数 3076 浏览 0 评论 0 收藏 0

2388. Change Null Values in a Table to the Previous Value

中文文档

Description

Table: CoffeeShop

+-------------+---------+
| Column Name | Type  |
+-------------+---------+
| id      | int   |
| drink     | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row in this table shows the order id and the name of the drink ordered. Some drink rows are nulls.

 

Write a solution to replace the null values of the drink with the name of the drink of the previous row that is not null. It is guaranteed that the drink on the first row of the table is not null.

Return the result table in the same order as the input.

The result format is shown in the following example.

 

Example 1:

Input: 
CoffeeShop table:
+----+-------------------+
| id | drink       |
+----+-------------------+
| 9  | Rum and Coke    |
| 6  | null        |
| 7  | null        |
| 3  | St Germain Spritz |
| 1  | Orange Margarita  |
| 2  | null        |
+----+-------------------+
Output: 
+----+-------------------+
| id | drink       |
+----+-------------------+
| 9  | Rum and Coke    |
| 6  | Rum and Coke    |
| 7  | Rum and Coke    |
| 3  | St Germain Spritz |
| 1  | Orange Margarita  |
| 2  | Orange Margarita  |
+----+-------------------+
Explanation: 
For ID 6, the previous value that is not null is from ID 9. We replace the null with "Rum and Coke".
For ID 7, the previous value that is not null is from ID 9. We replace the null with "Rum and Coke;.
For ID 2, the previous value that is not null is from ID 1. We replace the null with "Orange Margarita".
Note that the rows in the output are the same as in the input.

Solutions

Solution 1

# Write your MySQL query statement below
SELECT
  id,
  CASE
    WHEN drink IS NOT NULL THEN @cur := drink
    ELSE @cur
  END AS drink
FROM CoffeeShop;

Solution 2

# Write your MySQL query statement below
WITH
  S AS (
    SELECT *, ROW_NUMBER() OVER () AS rk
    FROM CoffeeShop
  ),
  T AS (
    SELECT
      *,
      SUM(
        CASE
          WHEN drink IS NULL THEN 0
          ELSE 1
        END
      ) OVER (ORDER BY rk) AS gid
    FROM S
  )
SELECT
  id,
  MAX(drink) OVER (
    PARTITION BY gid
    ORDER BY rk
  ) AS drink
FROM T;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文