复杂的组SQL查询

时间:2013-04-05 13:11:41

标签: sql group-by pivot

这是我的查询和结果;

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”,但它对我不起作用

抱歉我的英语。 -Thanks

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)