我已经找到了一些提取我想要的数据的查询,但我似乎无法把它们放在一起。我想将所有信息都放在一张表中。
SELECT MarketIdentifier, CurveType, VintageYear, Rate = Avg(RateValue) FROM #RateCurves GROUP BY MarketIdentifier, CurveType, VintageYear ORDER BY MarketIdentifier, CurveType, VintageYear
SELECT MarketIdentifier, CurveType, VintageYear, Obligation = Avg(ObligationValue) FROM #ObligationCurves GROUP BY MarketIdentifier, CurveType, VintageYear ORDER BY MarketIdentifier, CurveType, VintageYear
以上两个select语句产生两个不同的表,一个包含以下标题:
MarketIdentifier, CurveType, VintageYear, Rate
另一个:
MarketIdentifier, CurveType, VintageYear, Obligation
我只想输出:
MarketIdentifier, CurveType, VintageYear, Obligation, Rate
我尝试过JOIN,UNION,UNION ALL等多种不同的组合。其中一些组合会产生所需的表格格式但值不正确。我确信这是我非常缺乏的基础。
答案 0 :(得分:1)
你需要在两个句子中都有相同的字段。试试吧:
SELECT MarketIdentifier, CurveType, VintageYear, NULL as Obligation , Rate = Avg(RateValue)
FROM #RateCurves
GROUP BY MarketIdentifier, CurveType, VintageYear
ORDER BY MarketIdentifier, CurveType, VintageYear
UNION
SELECT MarketIdentifier, CurveType, VintageYear, Obligation = Avg(ObligationValue), NULL as Rate
FROM #ObligationCurves
GROUP BY MarketIdentifier, CurveType, VintageYear
ORDER BY MarketIdentifier, CurveType, VintageYear;
答案 1 :(得分:1)
一种方法是将group by
结果放在派生表t1
和t2
中,然后按照您要分组的列加入。
下面的查询假设两个查询每个(MarketIdentifier,CurveType,VintageYear)组合都有1行。即,不会有(MarketIdentifier,CurveType,VintageYear)在一个表中但不在另一个表中。否则,您必须根据所需的行进行左连接或完全连接。
select * from (
your first query here
) t1 inner join (
your second query here
) t2 on t2.MarketIdentifier = t1.MarketIdentifier
and t2.CurveType = t1.CurveType
and t2.VintageYear = t1.VintageYear