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

时间:2015-01-23 23:32:47

标签: mysql sql sql-server sql-server-2008

所以基本上我的代码涉及一个创建的表,其中最后一列是前两列的SUM,其中第一列来自表X,两列中的第二列来自'INNER JOIN OF表X与表Y'。

但是,我想通过'COUNTERPARTY'对所有这三列进行分组,'COUNTERPARTY'是一个变量,它在'表X'和'表1中的表X的内部连接'中同时出现。

棘手的部分是会有一些COUNTERPARTIES我们有数据集1(来自表X)和一些COUNTERPARTIES我们有数据集2(来自表X的INNER JOIN和表Y)和SOME因为我们有两个数据集!我希望包括交叉口以及门户,但是只有在检查了一个名为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

1 个答案:

答案 0 :(得分:-1)

要做的是实际使用UNION,以便按顺序将三个表连接在一起,并从每个表中获取所需的属性。最终我设法完成了整个存储过程!