条件行编号 - PrestoSQL

问题描述 投票:0回答:1

我需要有关 PrestoSQL 查询的帮助。如果我的column_1 like语句为真,我只需将行号更改为下一个。目前我已将其设置为 0,但我尝试使用“滞后”“领先”函数和其他一些想法,但没有成功。

我的询问:

WITH
  "FileCTE" AS (
   SELECT
     "tipo"
   , "column_1"
   , "Debe"
   , "Haber"
   , "Fecha"
   , "Numero"
   , "ROW_NUMBER"() OVER () "row"
   , "Saldo"
   , "Saldo_inicial"
   , "file_name"
   FROM
     "e90df27ca05f47da96d0b3966744739b"."d1c533d450b2490f945966ae78b5f830"
) 
SELECT
  "FileCTE"."tipo"
, (CASE WHEN ("FileCTE"."column_1" LIKE '%Cuenta%') THEN "row_number"() OVER () ELSE 0 END) "row"
, "FileCTE"."column_1"
, "FileCTE"."Debe"
, "FileCTE"."Haber"
, "FileCTE"."Fecha" "Date"
, "FileCTE"."Numero" "number"
, "Saldo"
, "Saldo_inicial"
, "file_name"
FROM
  "FileCTE"

目前正在获取:

我需要这个->

sql database presto
1个回答
0
投票

PostgreSQL 查询

此查询分析 tblRowNum_Test 表,根据存在情况计算累积组数 column_1 中文本“value”的值,并根据该组编号为行分配密集排名, 导致最终的行号输出。

请根据您的情况更改表格和案例条件。

-- Create the table
DROP TABLE IF EXISTS tblRowNum_Test;

CREATE TABLE tblRowNum_Test (
    id SERIAL PRIMARY KEY,    
    column_1 TEXT
);

-- Insert 10 records with varying empty values
INSERT INTO tblRowNum_Test (column_1)
VALUES
    ('Value1'), (''), ('Value2'),     
    (''), (''), ('Value3');            

-- Analyze the data with row numbering and grouping
WITH RankedData AS (
    SELECT
        id,
        column_1,
        SUM(CASE WHEN lower(column_1) LIKE '%value%' THEN 1 ELSE 0 END)
            OVER (ORDER BY id) AS group_number -- Calculate a cumulative group number based on 'value' presence
    FROM tblRowNum_Test
)
SELECT
    id,
    column_1,
    group_number,                      -- Display the calculated group number
    DENSE_RANK() OVER (ORDER BY group_number) AS final_row_number   -- Assign a dense rank based on the group number
FROM RankedData;
© www.soinside.com 2019 - 2024. All rights reserved.