このコードは、ピボットされた複数のテーブルからの情報を表示するようになりました。これで、このコードはほぼ希望どおりに機能するようになりました(現在、何かに取り組んでいます。これ以上の質問はありません)。
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, '+@colsNull+' 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('+@cols+')) piv'
execute(@query)
select * from ##tempz