これにはUNPIVOT
andを使用できます。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、コメントで、機能のないSQLiteを使用していると述べましたPIVOT
。UNION ALL
ただし、 を使用してから、 を使用した集計関数を使用してこれを行うことができます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