查询多个表格/视图并将结果放入#Temp(我使用MS SQL SERVER 2014)时,我得到以下结果
问题是我无法在每个组织的1行上获得所有相关数据。对于每个“额外”值,我都会得到一个新行,因此您会得到多行,从而得到未修改的结果。
Rows |OrgNumb|OrgNam |ProdNam| ValDec |AttrC | AttrV |
1 | 115 | Org1 | Acc | 1.00 | Number | 09133444 |
2 | 115 | Org1 | Acc | 1.00 | SBI | 1089 |
3 | 115 | Org1 | Fac | 1.00 | Number | 09133444 |
4 | 115 | Org1 | Fac | 1.00 | SBI | 1089 |
5 | 115 | Org1 | Rel | 1.00 | Number | 09133444 |
6 | 115 | Org1 | Rel | 1.00 | SBI | 1089 |
7 | 119 | Org2 | Ord | 1.00 | Number | 05558794 |
8 | 119 | Org2 | Ord | 1.00 | SBI | 1089 |
我需要得到以下结果:
Rows |OrgNum |OrgNam|ProdN1|ValDec1|ProdN2|ValDec2|ProdN3|ValDec3|AttrC1 |AttrV1 |AttrC2 |AttrV2|
1 | 115 | Org1 | Acc | 1.00 | Fac | 1.00 | Rel | 1.00 |Number | 09133444 | SBI | 1089 |
2 | 119 | Org1 | Ord | 1.00 | | | | |Number | 05558794 | SBI | 1089 |
还有更多列,但这些列是atm必不可少的列,与本示例不同,并非每个属性(AttrC1)都有值。
我做了具有类似目的的东西,但是源数据要简单得多(下面的代码)。因此,我要做的第一件事是将其基于以下查询,但返回错误的数据。然后,我使用Pivot,stuff / XML PATH进行了尝试,但是没有一个给我正确的结果。我看了@countles的例子,但没有一个例子能帮到我。
SELECT Period, Debitor,
MAX( CASE WHEN RN = 1 THEN Product ELSE NULL END ) AS Product1,
SUM( CASE WHEN RN = 1 THEN Amount ELSE NULL END ) AS Amount1,
MAX( CASE WHEN RN = 2 THEN Product ELSE NULL END ) AS Product2,
---- and so on
SUM( CASE WHEN RN = 14 THEN Amount ELSE NULL END ) AS Amount14,
SUM( price * Amount ) AS [Net price]
FROM (
SELECT ROW_NUMBER() OVER ( PARTITION BY Debitor, Debitor ORDER BY Period ) AS RN, *
FROM #TempVF
) AS RI
GROUP BY Period, Debitor
答案 0 :(得分:0)
以下内容可能会对您有所帮助:
DECLARE @cols AS VARCHAR(MAX), @query AS VARCHAR(MAX);
SET @cols = STUFF((select distinct ',
MAX(CASE WHEN ProdNam=''' + CAST(ProdNam as varchar(100)) + ''' THEN ProdNam ELSE '''' END) AS [ProdN' + CAST(sno as varchar(10)) +']
,MAX(CASE WHEN ValDec=''' + CAST(ValDec as varchar(100)) + ''' THEN ValDec ELSE '''' END) AS [ValDec' + CAST(sno as varchar(10)) +']
,MAX(CASE WHEN AttrC=''' + CAST(AttrC as varchar(100)) + ''' THEN AttrC ELSE '''' END) AS [AttrC' + CAST(sno as varchar(10)) +']
,MAX(CASE WHEN AttrV=''' + CAST(AttrV as varchar(100)) + ''' THEN AttrV ELSE '''' END) AS [AttrV' + CAST(sno as varchar(10)) +']'
/*---------------------------------you can add other columns similar to the above here----------------------------------*/
FROM #t
FOR XML PATH(''),type).value('.','varchar(max)'),1,2,'')
exec ('SELECT 1 '' '', OrgNumb, OrgNam, ' + @Cols +' FROM #t group by OrgNumb, OrgNam')
请找到数据库<>小提琴 here 。