使用两个单独的导入视图和单独的计算按同一列/变量分组

Grouping by same column / variable using two separate imported views and separate calculations

所以基本上我的代码涉及创建一个 table,它的最后一列是前两列的总和,两列中的第一列来自 table X,第二列来自 table X来自 'INNER JOIN OF table X with table Y' 的两列。

但是,我想通过 'COUNTERPARTY' 对所有三列进行分组,该变量同时存在于 'table X' 和 'INNER JOIN OF TABLE X WITH TABLE Y.'

棘手的部分是,会有一些我们有数据集 1(来自 TABLE X)的国家和一些我们有数据集 2(来自 INNER JOIN OF table X 和 table Y) 以及我们拥有两个数据集的一些原因!我想包括交叉点和异常值,但只有在对照名为 c.COUNTERPTY.

的交易对手的主密钥进行检查之后

请仔细阅读下面的代码,看看上面的解释与手头的问题有何关联。对于代码的长度,我深表歉意。

select 
p.Name as ENTITY, t.[Counterparty Code],  c.CNTRPTY_DS as COUNTERPARTY, cs.Tier,

... irrelevant code removed

sum((t.[Current value decimal] - t.[Trade price decimal])/100 * case when t.[Buy Sell Code] = 'B' 
then  1 else -1 end * t.[Open Amount]) as [OPEN MTM ($)],

sum((t2.[Weighted Average Settled Pair Off Price] - t2.[Trade price decimal])/100 * case when t2.[Buy Sell Code] = 'B' 
then  1 else -1 end * ISNULL(PO.[Pairoff Amount],0)) as [Unsettled Pairoffs/ AOTs ($)],

sum((t.[Current value decimal] - t.[Trade price decimal])/100 * case when t.[Buy Sell Code] = 'B' 
then  1 else -1 end * t.[Open Amount]) + sum((t2.[Weighted Average Settled Pair Off Price] - t2.[Trade price decimal])/100 * case when t2.[Buy Sell Code] = 'B' 
then  1 else -1 end * ISNULL(PO.[Pairoff Amount],0)) as [TOTAL MTM Exposure ($)]

from
[la-w08-qrm-db-1].qrmprod.dbo.vw_QRM_Trades t2
inner join 
[la-w08-qrm-db-1].qrmprod.dbo.VW_QRM_TRADE_PAIROFFS PO 
ON 
PO.[In Ticket Number] = t2.[Ticket number] 
and PO.[Portfolio ID] = t2.[Portfolio ID]
and t2.[derivative type] = 'F'                      -- note repeat below
and t2.[forward type] ='MBS'                        
and t2.[Counterparty Code] not in ('PLS', 'PNCO')
and t2.[Portfolio ID] in  (1,7)
and t2.[Settlement date] > GETDATE(),

prod.dbo.vw_QRM_Trades t,
prod.dbo.portdesc p,
prod.dbo.cptyall c, 
prod.dbo.VW_MB_ACTIVE_RUN r,
pulsar.dbo.CntrPrtySetup CS,
pulsar.dbo.CntrPrtyTiers CT
where
 r.mrktid =  1 
 And r.asmpid =  1 
 And r.cyclid =  1
 and r.compid = t.[Company ID]  
 and r.portid = t.[Portfolio ID]
 and p.PORTID = t.[Portfolio ID]
 and c.COUNTERPTY = t.[Counterparty Code] --key piece of code
 and cs.CNTRPTY_NO = c.CNTRPTY_NO
 and cs.PortID = t.[Portfolio ID]
 and cs.Tier = ct.Tier
 and t.[derivative type] = 'F'                   -- note repeat above
 and t.[forward type] ='MBS'
 and t.[Counterparty Code] not in ('PLS', 'PNCO')
 and t.[Portfolio ID] in  (1,7)
 and t.[Open Amount] > 0
 group by
 p.Name,  c.CNTRPTY_DS , t.[Counterparty Code], cs.Tier  -- yes this
 order by
 p.Name,  c.CNTRPTY_DS , t.[Counterparty Code], cs.Tier   -- and this

方法是实际使用 UNION 以便按顺序将三个表连接在一起,并为每个表提供我想要的属性。最终我确实设法完成了整个存储过程!