2

这是我的查询和结果;

select 
DATEADD(dd, DATEDIFF(dd, 0, PostDate), 0) as Date, 
Stores.Name StoreName, 
SUM(PosCash + PosCredit + PosBillCash + PosBillCredit) as Revenue  
from StoreRevenue
inner join Stores on Stores.ID = StoreRevenue.StoreID
group by DATEADD(dd, DATEDIFF(dd, 0, PostDate), 0), Stores.Name

结果: http: //prntscr.com/zaele

我想创建一个必须按日期和商店名称分组的表(结果)。

Date, Avcılar Mağaza, Ataşehir Mağaza
2013-03-04, 150, 200
2013-03-05, 200, 250
2013-03-06, 300, 150

子组的行(这些:2013-03-04、150、200)是每个商店的日期和收入我想要得到那种结果我也在 sql 中尝试过“pivot”但它对我不起作用

对不起我的英语不好。-谢谢

4

2 回答 2

2

试试这个:

WITH CTE
AS
(
    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
)
SELECT *
FROM CTE AS c
PIVOT
(
   SUM(Revenue)
   FOR StoreName IN ([Avcılar Mağaza],  [Ataşehir Mağaza], ...)
) AS p
于 2013-04-05T13:15:09.557 回答
2

您可以使用该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)
于 2013-04-05T13:16:24.960 回答