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 で「ピボット」も試しましたが、うまくいきません。

私の英語でごめんなさい。-ありがとう

4

2 に答える 2

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 に答える