修改后的问题——还需要 TradeID。
SELECT f.TradeID, f.PricingSecurityID, s.TotalQuantity
FROM FollowingTableStructure AS f
JOIN (SELECT PricingSecurityID, SUM(Quantity) AS TotalQuantity
FROM FollowingTableStructure
GROUP BY PricingSecurityId
) AS s ON f.PricingSecurityID = s.PricingSecurityID
我不完全相信这个查询是明智的,但那是你的问题。它可以很容易地扩展到处理其他表;只需添加适当的 JOIN 子句。
请记住在问题中包含表名——令人惊讶的是,SQL 问题被问到的频率却没有给表起名(所以不只是你忘记了)。
重新更新的问题
因此,最初的匿名表显然是,Fireball.dbo.Trade
或Fireball..Trade
。我可能会将 11 路 UNION 放入视图中,因为它可能会在多个地方使用。但是,忽略这一点,我们仍然可以将信息添加到您的查询中:
SELECT t.TradeId,
ISNULL(Securities.SecurityType,'Other') SecurityType,
Securities.TableName,
CASE
WHEN SecurityTrade.SecurityId IS NOT NULL THEN SecurityTrade.SecurityId
ELSE Trade.SecurityId
END AS PricingSecurityID,
s.TotalQuantity AS Quantity,
t.Price,
CASE
WHEN (t.Buy = 1 AND t.Long = 1) THEN 1
WHEN (t.Buy = 0 AND t.Long = 0) THEN 1
ELSE 0
END AS Position
FROM Fireball_Reporting..Trade AS t
JOIN (SELECT PricingSecurityID, SUM(Quantity) AS TotalQuantity
FROM Fireball_Reporting..Trade
GROUP BY PricingSecurityId
) AS s ON t.PricingSecurityID = s.PricingSecurityID
LEFT JOIN
(SELECT TradeId, 'Bond' SecurityType, 'Fireball.dbo.Bond' TableName FROM Fireball..CorpBondTrade
UNION
SELECT TradeId, 'IRS' SecurityType, 'Fireball.dbo.Bond' TableName FROM Fireball..IRPTrade
UNION
SELECT TradeId, 'Treasury' SecurityType, 'Fireball.dbo.Bond' TableName FROM Fireball..TreasuryTrade
UNION
SELECT TradeId, 'Index' SecurityType, 'Fireball.dbo.CDSIndex' TableName FROM Fireball..CreditIndexTrade
UNION
SELECT TradeId, 'CDS' SecurityType, 'Fireball.dbo.CDS' TableName FROM Fireball..CDSTrade WHERE IsSovereign = 0
UNION
SELECT TradeId, 'Sovereign CDS' SecurityType, 'Fireball.dbo.CDS' TableName FROM Fireball..CDSTrade WHERE IsSovereign = 1
UNION
SELECT TradeId, 'Equity Option' SecurityType, 'Fireball.dbo.EquityOption' TableName FROM Fireball..EquityOptionTrade
UNION
SELECT TradeId, 'Equity' SecurityType, 'Fireball.dbo.Equity' TableName FROM Fireball..EquityTrade
UNION
SELECT TradeId, 'Loan' SecurityType, 'Fireball.dbo.Loan' TableName FROM Fireball..LoanTrade
UNION
SELECT TradeId, 'Swaption' SecurityType, 'Fireball.dbo.Bond' TableName FROM Fireball..SwaptionTrade
UNION
SELECT TradeId, 'Preferred Stock' SecurityType, 'Fireball.dbo.Bond' TableName FROM Fireball..PreferredEquityTrade
--UNION
--SELECT TradeId, 'Bond' SecurityType FROM Fireball..BondTrade
) AS Securities ON Securities.TradeId = t.TradeId
LEFT JOIN
(SELECT TradeID, SecurityId
FROM Fireball..CDSTrade
UNION
SELECT TradeID, SecurityId
FROM Fireball..CreditIndexTrade
) AS SecurityTrade ON SecurityTrade.TradeId = t.TradeId
这主要是复制和粘贴 - 并重新格式化 - 您的查询,额外的子查询隐藏在 Trade 表之后的 FROM 子句中。如果是我的查询,我也会对最后两个子查询使用单字母(或其他短助记符)别名;我只是没有花时间研究什么是 SecurityTrade 和 Securities 的适当缩写。