您可以使用该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)