繁体   English   中英

没有分组的listagg函数

[英]listagg function without group by

我在select语句中有很多列,其中许多是派生计算。

我试图在select语句中使用listagg()将多行分组为一个,但不必按select语句中group by 沿着listagg() within group() over (partition by id)行。

现在我有一些类似的东西:

select id, listagg(distinct annual_bill_rate, ', ') within group (order by bill_rate) as annual_bill_rate, email, state
from table
group by 1,3,4

根据文档似乎无法避免这一组,但有替代方案吗? 我有 30 多个列,我无法按所有列分组。 谢谢!

样本数据:

id   bill_rate   email        state 
1    0.0035      a@gmail.com  NJ
1    0.0045      a@gmail.com  NJ
1    0.0055      a@gmail.com  NJ
2    0.0065      b@gmail.com  NY
2    0.0075      b@gmail.com  NY
3    0.0085      c@gmail.com  PA

期望的结果 - 没有 GROUP BY:

id   bill_rate                email        state 
1    0.0035, 0.0045, 0.0055   a@gmail.com  NJ
2    0.0065, 0.0075           b@gmail.com  NY
3    0.0085                   c@gmail.com  PA

这是避免键入 GROUP BY 的一个不太好的主意。 它几乎肯定会更慢,并且更难以阅读和理解。 如果我在生产代码中遇到这个问题,我会很不高兴:

WITH table_distinct AS 
(
    SELECT DISTINCT id, email, state
    FROM table
)
,table_group_by AS
(
    SELECT id, listagg(distinct annual_bill_rate, ', ') within group (order by bill_rate) as annual_bill_rate
    FROM table
    GROUP BY id
)
SELECT 
    td.*,
    tgb.annual_bill_rate        
FROM table_distinct td
    INNER JOIN table_group_by tgb
        ON td.id = tgb.id;

现在你真的只需要使用那个table_distinct CTE 的猴子来为你的结果集添加更多的列。

无需使用 Distinct 或 Group By 子句即可解决您的问题。 您也可以使用 LISTAGG 作为分析函数,然后可以使用 row_number 删除重复项。 公安局——

select * from
(select 
id, listagg(annual_bill_rate, ', ') within group (order by bill_rate) over (partition by id order by id) as annual_bill_rate,
email, state, row_number() over (partition by id order by id) RN
from table) Tab where RN=1;

暂无
暂无

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

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