好的,所以我前几天提出了关于一个支点的问题,主持人刚刚指出了另一个问题,这不是答案,但我在另一个网站上找到了自己的问题。这与同一个SQL有关,但我需要做一个双重支点。
这是我的代码
CREATE TABLE #tempBene
(accountID varchar(8),
beneName1 varchar(30),
beneamount1 decimal(12,0)
)
INSERT INTO #tempBene
(accountID, beneName, beneamount)
VALUES
('1', 'One', 1),
('1', 'OneTwo', 1),
('1', 'OneThree', 1),
('1', 'OneFour', 1),
('1', 'OneFive', 1),
('1', 'OneSix', 1),
('2', 'TwoOne', 2),
('2', 'TwoTwo', 2),
('2', 'TwoThree', 2),
('3', 'ThreeOne', 3),
('3', 'ThreeTwo', 3),
('3', 'ThreeThree', 3),
('4', 'FourOne', 4),
('4', 'FourTwo', 4),
('5', 'FiveOne', 5)
SELECT ACCOUNTID, [1] as BENE1, [2] as Bene2, [3] as Bene3, [4] as Bene4, [5] as Bene5
INTO #TempBene
FROM
(SELECT ACCOUNTID, BeneficiaryName
ROW_NUMBER() OVER (PARTITION BY AccountID ORDER BY ACCOUNTID)
AS ROWNUM
FROM #TempAccount
WHERE DELETEFLAG = 'N') a
PIVOT (MAX(BENEFICIARYName) FOR RowNUM IN ([1], [2], [3], [4], [5])) AS pvt
上面的第一个支点绕过聚合体并给出了我需要的部分内容。
我得到了
ACCOUNTID Bene1 BENE2 BENE3 BENE4 BENE5
1 one onetwo
2 twoone twotwo twothree twofour twofive
我需要什么,而我无法弄清楚如何包含一笔金额,因为我没有聚合。
我需要
AccountID Bene1 BeneAmt1 Bene2 BeneAmount2 ...
1 one 1 onetwo 1
2 onetwo 2 twotwo 2
很抱歉,如果这对某些人来说很简单,但是我无法添加每个记录的金额并维持我的支点。
由于
答案 0 :(得分:0)
你可以通过不使用PIVOT但使用条件聚合来实现。
select a.accountID,
MAX(CASE WHEN rowNum = 1 THEN beneName END) AS Bene1,
SUM(CASE WHEN rowNum = 1 THEN beneAmount END) AS BeneAmt1,
MAX(CASE WHEN rowNum = 2 THEN beneName END) AS Bene2,
SUM(CASE WHEN rowNum = 2 THEN beneAmount END) AS BeneAmt2,
MAX(CASE WHEN rowNum = 3 THEN beneName END) AS Bene3,
SUM(CASE WHEN rowNum = 3 THEN beneAmount END) AS BeneAmt3,
MAX(CASE WHEN rowNum = 4 THEN beneName END) AS Bene4,
SUM(CASE WHEN rowNum = 4 THEN beneAmount END) AS BeneAmt4,
MAX(CASE WHEN rowNum = 5 THEN beneName END) AS Bene5,
SUM(CASE WHEN rowNum = 5 THEN beneAmount END) AS BeneAmt5,
MAX(CASE WHEN rowNum = 6 THEN beneName END) AS Bene6,
SUM(CASE WHEN rowNum = 6 THEN beneAmount END) AS BeneAmt6
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY accountID ORDER BY accountID) AS rowNum
FROM #tempBene
) a
GROUP BY a.accountID