2013-02-04 82 views
0

此代碼現在顯示來自多個表的信息,這些表都是支持的 好的,所以現在這個代碼幾乎可以像我想要的那樣工作了(目前正在使用它,沒有更多的問題atm ):將多個表連接到數據透視表的動態表中

if (exists (select * from tempdb.INFORMATION_SCHEMA.TABLES where TABLE_NAME = '##tempz')) 
begin 
drop table ##tempz 
end 
else 
DECLARE @startDate datetime 
DECLARE @enddate datetime 
DECLARE @registernum int 
DECLARE @storename varchar(20) 
DECLARE @cashiername varchar(20) 
SET @startDate = '1/1/2011' 
SET @enddate = '1/1/2013' 
SET @registernum = 01 
SET @storename = '01' 
SET @cashiername = 'admin' 

DECLARE @cols AS NVARCHAR(MAX),@colsNull AS NVARCHAR(MAX),@query AS NVARCHAR(MAX) 
SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(c.CurrencyDesc) 
FROM rpPay p LEFT JOIN RPTrs r ON p.ReceiptNo = r.ReceiptNo LEFT JOIN Currencies c ON c.POSCurrency = LEFT(p.paytype,1) 
WHERE r.trsdate >= @startDate AND r.trsdate <= @enddate 
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') 

SELECT @colsNull = STUFF((SELECT DISTINCT ', IsNull(' + QUOTENAME(c.CurrencyDesc) +', 0) as '+ QUOTENAME(c.CurrencyDesc) 
FROM rpPay p LEFT JOIN RPTrs r ON p.ReceiptNo = r.ReceiptNo LEFT JOIN Currencies c ON LEFT(p.paytype,1) = c.POSCurrency 
WHERE r.trsdate >= @startDate AND r.trsdate <= @enddate 
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') 

--select @cols, @colsnull 

SET @query = 'select date, cashregister, storeid, cashier, '[email protected]+' into ##tempz 
FROM 
(SELECT cast(r.trsdate AS DATE) date,c.CurrencyDesc,p.amount,r.cashregister,r.storeid,r.cashier 
FROM rpPay p LEFT JOIN RPTrs r ON p.ReceiptNo = r.receiptno LEFT JOIN Currencies c ON LEFT(p.paytype,1) = c.POSCurrency 
WHERE r.trsdate >= '''+ convert(varchar(10), @startDate, 101) +''' AND r.trsdate <= '''+ convert(varchar(10), @endDate, 101) +''' 
) p 
pivot 
(sum(amount) FOR CurrencyDesc in('[email protected]+')) piv' 
execute(@query) 

select * from ##tempz 
+1

讓我們從你正在使用的RDBMS開始 – Lamak

+1

發佈你的全表結構會非常有幫助 – Taryn

+0

MsSQL 2008,rpPay有storeID,PayType,金額。貨幣具有POSCurrency(與rpPay.PayType相同)CurrencyDesc。 RPTrs有storeID,trsdate – JohnZ

回答

2

您沒有指定您所使用的RDBMS但我SQL服務器根據你前面的問題假設。根據有限的細節,你可以得到PIVOT的數據。

如果你提前知道時間的價值,那麼你可以硬編碼使用靜態支點的值:

select * 
from 
(
    select 
     cast(r.trsdate as DATE) date, 
     c.CurrencyDesc, 
     p.amount 
    from rpPay p 
    left join RPTrs r 
     on p.id = r.id 
    left join Currencies c 
     on p.PayType = c.PayType 
    where r.trsdate >= @startDate 
     and r.trsdate <= @enddate 
) src 
pivot 
(
    sum(amount) 
    for CurrencyDesc in (Amex, Cash, Visa, Check, [Gift Card]) 
) piv 

如果值是未知的,那麼你可以使用動態SQL:

declare @startDate datetime 
declare @enddate datetime 
    set @startDate = '1/1/12' 
set @enddate = '1/1/13' 
DECLARE @cols AS NVARCHAR(MAX), 
    @query AS NVARCHAR(MAX) 

select @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(c.CurrencyDesc) 
        from rpPay p 
        left join RPTrs r 
         on p.id = r.id 
        left join Currencies c 
         on p.PayType = c.PayType 
        where r.trsdate >= @startDate 
         and r.trsdate <= @enddate 
      FOR XML PATH(''), TYPE 
      ).value('.', 'NVARCHAR(MAX)') 
     ,1,1,'') 

set @query 
    = 'select date, '[email protected]+' 
     from 
     (
     select 
      cast(r.trsdate as DATE) date, 
      c.CurrencyDesc, 
      p.amount 
     from rpPay p 
     left join RPTrs r 
      on p.id = r.id 
     left join Currencies c 
      on p.PayType = c.PayType 
     where r.trsdate >= '''+ convert(varchar(10), @startDate, 101) +''' 
      and r.trsdate <= '''+ convert(varchar(10), @endDate, 101) +''' 
     ) p 
     pivot 
     (
      sum(amount) 
      for CurrencyDesc in('[email protected]+') 
     ) piv' 

execute(@query) 

編輯#1,根據你的編輯問題,你可以使用:

declare @startDate datetime 
declare @enddate datetime 
declare @registernum int 
declare @storename int 
declare @cashiername varchar(20) 
set @startDate = '1/1/2012' 
set @enddate = '1/1/2013' 
set @registernum = 01 
set @storename = '01' 
set @cashiername = 'admin' 

DECLARE @cols AS NVARCHAR(MAX), 
    @colsNull AS NVARCHAR(MAX), 
    @query AS NVARCHAR(MAX) 

select @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(c.CurrencyDesc) 
         from rpPay p 
         left join RPTrs r 
          on p.ReceiptNo = r.ReceiptNo 
         left join Currencies c 
          on p.PayType = c.POSCurrency 
         where r.trsdate >= @startDate and r.trsdate <= @enddate 
          and cashregister = @registernum 
          and r.storeid = @storename 
          and cashier = @cashiername 
         FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') 

select @colsNull = STUFF((SELECT DISTINCT ', IsNull(' + QUOTENAME(c.CurrencyDesc) +', 0) as '+ QUOTENAME(c.CurrencyDesc) 
         from rpPay p 
         left join RPTrs r 
          on p.ReceiptNo = r.ReceiptNo 
         left join Currencies c 
          on p.PayType = c.POSCurrency 
         where r.trsdate >= @startDate and r.trsdate <= @enddate 
          and cashregister = @registernum 
          and r.storeid = @storename 
          and cashier = @cashiername 
         FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') 

--select @cols, @colsnull 

set @query = 'select date, cashregister, storeid, cashier, '[email protected]+' 
       from 
       (
        select cast(r.trsdate as DATE) date, 
         c.CurrencyDesc, 
         p.amount, 
         r.cashregister, 
         r.storeid, 
         r.cashier 
        from rpPay p 
        left join RPTrs r 
         on p.ReceiptNo = r.receiptno 
        left join Currencies c 
         on p.PayType = c.POSCurrency 
        where r.trsdate >= '''+ convert(varchar(10), @startDate, 101) +''' 
         and r.trsdate <= '''+ convert(varchar(10), @endDate, 101) +''' 
         and cashregister = '''+cast(@registernum as varchar(10))+''' 
         and r.storeid = '''+cast(@storename as varchar(50))+''' 
         and r.cashier = '''[email protected]+''' 
       ) p 
       pivot 
       (
        sum(amount) 
        for CurrencyDesc in('[email protected]+') 
       ) piv' 

execute(@query) 

SQL Fiddle with Demo

+0

這不完全一樣,但FWIW http://www.sqlfiddle.com/#!6/4dea4/4 –

+0

@JohnZ在你的更新後看到我的編輯OP – Taryn

+0

我得到這些錯誤:Msg 102,Level 15,State 1,Line 1 'Cash'附近語法不正確。 Msg 105,Level 15,State 1,Line 19 字符串' )p 樞軸 (在[Cash],[MasterCard],[Offline C.Card ],[C.Card],[Str Cr],[Visa/MC],[現金兌換],[禮品卡],[Amex]))。 – JohnZ