My first table dbo.Port
contains aggregated details about each portfolio
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
My second table dbo.Security
contains details about each portfolios individual securities
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
I can retrieve the modal country for portfolio 1 with the below separate query. which isUS
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
What I want my query to return is to return a joined query that selects the modal values of country and sector for each portfolio. Does anyone know how to incorporate this query into the first query or any other method so that I can retrieve MODE(dbo.Security.Country)
etc. for each portfolio so that I end up with the below table
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
Desired 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
First of all, your query to retrieve the model country for portfolio 1 should include an ORDER BY
clause otherwise it will just return the country of the first row that matches the WHERE
clause.
Secondly, you could achieve the desired output using inline queries:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With