7

我的第一个表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 的模式国家。这是US

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
4

1 回答 1

2

首先,您检索投资组合 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
于 2013-08-02T10:35:38.203 回答