首页 > 解决方案 > 使用 Plsql 在一张表中需要不同数量的不同地址、ID 等

问题描述

请在以下情况下需要帮助。我想要使​​用 plsql 或在一个表中具有不同数量的不同地址、ID 等

例如下面是当前表

Address            aRea zipcode ID      Amount  amount2 qua number
123 Howe's drive    AL  1234    1234567  100     20      1  666666
123 Howe's drive    AL  1234    1234567   5      05      2  abcccc
123 east drive      AZ  456     8910112  200     11      1  777777
123 east drive      AZ  456     8910112   5       5      2   SDN133
116 WOOD Ave        NL  1234    2325890  3.23   1.25     1  10483210
116 WOOD Ave        NL  1234    2325890  3.24   1.26     2  10483211

在此处输入图像描述

我需要如下输出。

Address            aRea zipcode ID      Amount  amount2 qua number
123 Howe's drive    AL  1234    1234567  100     20      1  666666
                                          5      05      2  abcccc
123 east drive      AZ  456     8910112  200     11      1  777777
                                          5       5      2   SDN133
116 WOOD Ave        NL  1234    2325890  3.23   1.25     1  10483210
                                         3.24   1.26     2  10483211

在此处输入图像描述

标签: sqlplsqlgoogle-bigquery

解决方案


这种类型的任务通常最好在应用程序端完成。

可以使用 SQL 执行此操作 - 但您需要一列来一致地对记录进行排序:

select
    case when rn = 1 then address  end as address,
    case when rn = 1 then area     end as area,
    case when rn = 1 then zipcode end as zipcode,
    case when rn = 1 then id       end as id,
    amount,
    amount2,
    qua,
    number
from (
    select 
        t.*, 
        row_number() over(
            partition by address, area, zipcode, id 
            order by ??
        ) rn
    from mytable t
) t
order by address, area, zipcode, id, ??

窗口函数的partition by子句列出了要“分组”在一起的列;您可以根据需要对其进行修改。

order by子句row_number()指示应如何在分区内对行进行排序:您需要决定要使用哪一列(或一组列)。为了使输出 tu 有意义,您还需要order by在查询中添加一个子句,其中将重复分区和排序列。


推荐阅读