gpt4 book ai didi

sql - 从另一个表创建 View

转载 作者:行者123 更新时间:2023-12-04 21:22:43 25 4
gpt4 key购买 nike

我想从另一个表创建一个 View ..

当前 View 有以下内容(图片 1):

enter image description here

尝试从上面的 View 中获取输出(图 2),即对这些列中的值进行分组:

enter image description here

最佳答案

一种方法是取消数据透视然后重新聚合:

select w,
sum(case when i = 0 then 1 else 0 end) as w1,
sum(case when i = 1 then 1 else 0 end) as w2,
sum(case when i = 2 then 1 else 0 end) as w3,
sum(case when i = 3 then 1 else 0 end) as w4
from (select array[w1, w2, w3, w4] ws
from t
) t cross join
unnest(ws) w with offset i
group by w;

这是一个更完整的例子:

with t as (
select 1 as slno, '<5' as w1, '<5' as w2, '<5' as w3, '<5' as w4 union all
select 1 as slno, '<5' as w1, '5 to 10' as w2, '<5' as w3, '5 to 10' as w4
)
select w,
sum(case when i = 0 then 1 else 0 end) as w1,
sum(case when i = 1 then 1 else 0 end) as w2,
sum(case when i = 2 then 1 else 0 end) as w3,
sum(case when i = 3 then 1 else 0 end) as w4
from (select array[w1, w2, w3, w4] as ws
from t
) t cross join
unnest(ws) w with offset i
group by w;

关于sql - 从另一个表创建 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51664027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com