我在select
语句中有很多列,其中许多是派生计算。
我试图在listagg()
语句中使用select
将多行组合成一行,但不必在group by
语句中使用select
其余列。沿着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 [email protected] NJ
1 0.0045 [email protected] NJ
1 0.0055 [email protected] NJ
2 0.0065 [email protected] NY
2 0.0075 [email protected] NY
3 0.0085 [email protected] PA
期望的结果 - 没有GROUP BY:
id bill_rate email state
1 0.0035, 0.0045, 0.0055 [email protected] NJ
2 0.0065, 0.0075 [email protected] NY
3 0.0085 [email protected] 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的猴子来为你的结果集添加更多的列。