gpt4 book ai didi

SQL pivot 并填充 NULL 值

转载 作者:搜寻专家 更新时间:2023-10-30 22:32:50 25 4
gpt4 key购买 nike

在 SQL (SQLite) 中,我有一个“权重”表,其中包含每个项目大小的权重,例如

item size    weight
---- ---- ------
a small 1.2
a medium 2.2
b medium 1.6
c small 1.0
c medium 1.5
c large 2.0

我如何旋转表格,使“项目”列的每个唯一值各占一行,然后为“大小”中出现的每个值创建列。如果元素的给定尺寸不存在重量,则会插入 NULL 值,例如

item small medium large
---- ----- ------ -----
a 1.2 2.2 NULL
b NULL 1.6 NULL
c 1.0 1.5 2.0

最佳答案

Select item
,max(case when size='small' then weight else null end) as small
,max(case when size='medium' then weight else null end) as medium
,max(case when size='large' then weight else null end) as large
From weights
Group By item

EDIT - Dynamic version

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName([size]) From YourTable Order by 1 For XML Path('')),1,1,'') 
Select @SQL = '
Select [Item],' + @SQL + '
From YourTable
Pivot (max(weight) For [size] in (' + @SQL + ') ) p'
Exec(@SQL);

注意:我已经很多年没有使用 SQLite 了。不确定这种动态方法是否有效

关于SQL pivot 并填充 NULL 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41471498/

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