我的第一个表dbo.Port
包含有关每个投资组合的汇总详细信息
Portfolio Yield Duration Coupon
Port1 0.62 1.10 0.98
Port2 0.52 0.91 2.46
Port3 0.40 0.70 0.37
我的第二个表dbo.Security
包含有关每个投资组合单个证券的详细信息
Portfolio Security Yield Duration Coupon Country Sector MarketValue
Port1 Sec1 0.35 0.50 2.25 US CORP 386.17
Port1 Sec2 0.16 0.23 1.75 UK CORP 224.64
Port1 Sec3 0.98 1.96 3.00 US CORP 148.00
Port1 Sec4 0.78 1.40 0.00 DE SOV 980.07
Port2 Sec1 0.35 0.50 2.25 US CORP 386.17
Port2 Sec3 0.98 1.96 3.00 US CORP 148.00
Port3 Sec1 0.35 0.50 2.25 US CORP 386.17
Port3 Sec4 0.78 1.40 0.00 DE SOV 980.07
Port3 Sec5 0.03 0.06 0.00 DE SOV 952.36
我可以使用下面的单独查询检索投资组合 1 的模态国家/地区。这是美国
SELECT x.Country
FROM (
SELECT TOP 1 COUNT(dbo.Security.Country) as Count ,dbo.Security.Country
FROM dbo.Port
INNER JOIN dbo.Security ON (dbo.Port.Portfolio = dbo.Security.Portfolio)
WHERE dbo.Port.Portfolio = 'Port1'
GROUP BY dbo.Security.Country
ORDER BY Count DESC
) x
我希望查询返回的是返回一个连接查询,该查询为每个投资组合选择国家和部门的模态值。有谁知道如何将此查询合并到第一个查询或任何其他方法中,以便我可以为每个投资组合检索 MODE(dbo.Security.Country) 等,以便我最终得到下表
Portfolio Yield Duration Coupon Market Value Country Sector
Port1 0.62 1.10 0.98 1738.88 US CORP
Port2 0.52 0.91 2.46 534.17 US CORP
Port3 0.40 0.70 0.37 2318.60 DE SOV
所需的 SQL
SELECT
dbo.Port.Portfolio
,dbo.Port.Yield
,dbo.Port.Duration
,dbo.Port.Coupon
,SUM(dbo.Security.MarketValue)
--Not working
,MODE(dbo.Security.Country)
,MODE(dbo.Security.Sector)
--Not working
FROM dbo.Port
INNER JOIN dbo.Security ON (dbo.Port.Portfolio = dbo.Security.Portfolio)
GROUP BY
dbo.Port.Portfolio
,dbo.Port.Yield
,dbo.Port.Duration
,dbo.Port.Coupon
最佳答案
首先,检索投资组合 1 的模型国家/地区的查询应包含 ORDER BY
子句,否则它将仅返回与 WHERE
匹配的第一行的国家/地区条款。
其次,您可以使用内联查询获得所需的输出:
SELECT
P.Portfolio
,P.Yield
,P.Duration
,P.Coupon
,SUM(S.MarketValue)
,( SELECT TOP 1 Country FROM dbo.Security WHERE Portfolio = P.Portfolio GROUP BY Country ORDER BY COUNT(*) DESC ) Country
,( SELECT TOP 1 Sector FROM dbo.Security WHERE Portfolio = P.Portfolio GROUP BY Sector ORDER BY COUNT(*) DESC ) Sector
FROM dbo.Port P
INNER JOIN dbo.Security S ON (P.Portfolio = S.Portfolio)
GROUP BY
P.Portfolio
,P.Yield
,P.Duration
,P.Coupon
关于sql - SELECT 模式/模态值 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18013871/