SQL 旋转并填充 NULL 值
SQL pivot and fill in NULL values
在 SQL(SQLite)中,我有一个 table 'weights' 包含每个项目大小的重量,例如
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
我如何旋转 table 以便我有 'item' 列,每个唯一值一行,然后为 'size' 中出现的每个值创建列。如果给定尺寸的商品没有重量,则插入 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 了。不确定这种动态方法是否有效
NULL 是条件不满足时 CASE 的结果。
Select item
,max(case when size='small' then weight end) as small
,max(case when size='medium' then weight end) as medium
,max(case when size='large' then weight end) as large
From weights
Group By item
或
Select item
,max(case size when 'small' then weight end) as small
,max(case size when 'medium' then weight end) as medium
,max(case size when 'large' then weight end) as large
From weights
Group By item
在 SQL(SQLite)中,我有一个 table 'weights' 包含每个项目大小的重量,例如
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
我如何旋转 table 以便我有 'item' 列,每个唯一值一行,然后为 'size' 中出现的每个值创建列。如果给定尺寸的商品没有重量,则插入 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 了。不确定这种动态方法是否有效
NULL 是条件不满足时 CASE 的结果。
Select item
,max(case when size='small' then weight end) as small
,max(case when size='medium' then weight end) as medium
,max(case when size='large' then weight end) as large
From weights
Group By item
或
Select item
,max(case size when 'small' then weight end) as small
,max(case size when 'medium' then weight end) as medium
,max(case size when 'large' then weight end) as large
From weights
Group By item