您可以为此使用UNPIVOT
和:PIVOT
这是查询的静态版本 - 静态版本意味着您对值进行硬编码。
select *
from
(
select *
from
(
select priority, timing1, timing2, timing3
from yourtable
) x
unpivot
(
value
for field in (timing1, timing2, timing3)
) u
) x1
pivot
(
sum(value)
for priority in ([0], [1], [2])
) p
您也可以动态执行此操作:
DECLARE @colsUnpivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX),
@colsPivot as NVARCHAR(MAX),
@colsPivotName as NVARCHAR(MAX)
select @colsUnpivot = stuff((select ','+ quotename(C.name)
from sys.columns as C
where C.object_id = object_id('yourtable') and
C.name LIKE 'timing%'
for xml path('')), 1, 1, '')
select @colsPivot =
STUFF((SELECT distinct ',' + Quotename(priority)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsPivotName =
STUFF((SELECT distinct ','
+ Quotename(priority) + ' as Priority' + cast(priority as varchar(1))
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'select col, '+ @colsPivotName +'
from
(
select priority, val, col
from
(
select priority, ' + @colsUnpivot + '
from yourtable
) x
unpivot
(
val
for col in ('+ @colsUnpivot +')
) u
) x1
pivot
(
sum(val)
for priority in ( '+ @colspivot + ')
) p'
exec(@query)
编辑#1,您在评论中说您使用的是没有PIVOT
功能的 SQLite。但是您仍然可以使用 aUNION ALL
然后使用带有 a 的聚合函数来执行此操作CASE
:
select col,
sum(case when priority = 0 then value end) as Priority0,
sum(case when priority = 1 then value end) as Priority1,
sum(case when priority = 2 then value end) as Priority2
from
(
select priority, timing1 as value, 'timing1' as col
from yourtable
union all
select priority, timing2 as value, 'timing2' as col
from yourtable
union all
select priority, timing3 as value, 'timing3' as col
from yourtable
) x
group by col