関数を使用してPIVOT
、データを行から列に変換できます。
select *
from
(
select
DATEADD(dd, DATEDIFF(dd, 0, PostDate), 0) as Date,
Stores.Name StoreName,
(PosCash + PosCredit + PosBillCash + PosBillCredit) as Revenue
from StoreRevenue
inner join Stores
on Stores.ID = StoreRevenue.StoreID
) d
pivot
(
sum(Revenue)
for StoreName in ([Avcılar Mağaza], [Ataşehir Mağaza]..)
) piv;
または、次のように集計関数を使用できますCASE
。
select DATEADD(dd, DATEDIFF(dd, 0, PostDate), 0) as Date,
sum(case when Stores.Name = 'Avcılar Mağaza'
then PosCash + PosCredit + PosBillCash + PosBillCredit end) as [Avcılar Mağaza],
sum(case when Stores.Name = 'Ataşehir Mağaza'
then PosCash + PosCredit + PosBillCash + PosBillCredit end) as [Ataşehir Mağaza]
from StoreRevenue
inner join Stores
on Stores.ID = StoreRevenue.StoreID
group by DATEADD(dd, DATEDIFF(dd, 0, PostDate), 0)
ストアの数が不明な場合は、動的 SQL を使用できます。
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(name)
from Stores
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Date, ' + @cols + '
from
(
select
DATEADD(dd, DATEDIFF(dd, 0, PostDate), 0) as Date,
Stores.Name StoreName,
(PosCash + PosCredit + PosBillCash + PosBillCredit) as Revenue
from StoreRevenue
inner join Stores
on Stores.ID = StoreRevenue.StoreID
) x
pivot
(
sum(Revenue)
for StoreName in (' + @cols + ')
) p '
execute(@query)