这是我用于此查询的表。我需要找到一种将所有表格结果合并到一个表格中的方法。
CREATE TABLE #temp
(
ACCT_NR VARCHAR(30)
, DEDNCODE VARCHAR(30)
, DEDN_ALPHA VARCHAR(12)
, AMOUNT DECIMAL(10,2)
, AGING INT
, PAY_PERIOD CHAR(6)
, [TYPE] CHAR(1)
)
INSERT INTO #temp (ACCT_NR, DEDNCODE, DEDN_ALPHA, AMOUNT, AGING, PAY_PERIOD, [TYPE])
VALUES
('20110101401', '159', 'MEM PLAN', 16.00 , 0, '012013', 'S'),
('20110101401', '557', 'PHILHEALTH', 175.00 , 0, '012013', 'S'),
('20110101401', '617', 'S G T I', 6.00 , 0, '012013', 'S'),
('20110101401', '634', 'PAGIBIG C', 100.00 , 0, '012013', 'S'),
('20110101401', '761', 'PSMBFI EP', 445.02 , 0, '012013', 'S'),
('20110101401', '762', 'PSMBFI BG', 25.00 , 0, '012013', 'S'),
('20110101401', '009', 'PSSLAI', 2000.00, 0, '012013', 'N'),
('20110101401', '350', 'W TAX', 786.80 , 0, '012013', 'N'),
('20110101401', '551', 'AFPMBA ADDL', 1054.90, 0, '012013', 'N'),
('20110101401', '768', 'PSMBFI EL', 3277.78, 7, '012013', 'N')
INSERT INTO #temp (ACCT_NR, DEDNCODE, DEDN_ALPHA, AMOUNT, AGING, PAY_PERIOD, [TYPE])
VALUES
('20110101401', '159', 'MEM PLAN', 16.00 , 0, '022013', 'S'),
('20110101401', '557', 'PHILHEALTH', 175.00 , 0, '022013', 'S'),
('20110101401', '617', 'S G T I', 6.00 , 0, '022013', 'S'),
('20110101401', '634', 'PAGIBIG C', 100.00 , 0, '022013', 'S'),
('20110101401', '761', 'PSMBFI EP', 445.02 , 0, '022013', 'S'),
('20110101401', '762', 'PSMBFI BG', 25.00 , 0, '022013', 'S'),
('20110101401', '009', 'PSSLAI', 2000.00, 0, '022013', 'N'),
('20110101401', '350', 'W TAX', 786.80 , 0, '022013', 'N'),
('20110101401', '551', 'AFPMBA ADDL', 1054.90, 0, '022013', 'N'),
('20110101401', '768', 'PSMBFI EL', 3277.78, 7, '022013', 'N')
这是我的代码,它生成的结果给了我很多表
DECLARE @cols AS NVARCHAR(MAX),
@acctnr NVARCHAR(MAX),
@payperiod NVARCHAR(MAX),
@payperiod2 NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @acctnr = '19991200184';
SET @payperiod = '012013';
SET @payperiod2= '052013';
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(p.DEDN_ALPHA)
from #temp p
where ACCT_NR = @acctnr
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
while CONVERT(int,@payperiod) <= CONVERT(int,@payperiod2)
begin
set @query = 'SELECT ' + @cols + ' from
(
SELECT AMOUNT, DEDN_ALPHA
FROM #temp
where ACCT_NR = Cast((' + @acctnr + ') As nvarchar(30)) and PAY_PERIOD = ' + @payperiod + '
) x
pivot
(
min(amount)
for DEDN_ALPHA in (' + @cols + ')
) p '
execute(@query)
set @payperiod = '0' + CONVERT(nvarchar, convert(int,@payperiod) + 10000)
set @payperiod = REPLACE(STR(@payperiod, 6), SPACE(1), '0')
end
问题是结果给了我很多表。我怎样才能使所有结果都在一张表中?
提前致谢