Click here to Skip to main content
15,910,411 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
CREATE TABLE ProfitAndLoss (
 ProfitAndLossId BIGINT IDENTITY(1,1) PRIMARY KEY NOT NULL,
 ValueDate DATE NOT NULL,
 FundName VARCHAR(50) NOT NULL,
 StrategyName VARCHAR(50) NOT NULL,
 MarketName VARCHAR(50) NOT NULL,
 DailyPnlUsd FLOAT NOT NULL,
 MtdPnlUsd FLOAT NOT NULL,
 YtdPnlUsd FLOAT NOT NULL


What I have tried:

how do i write a query to retrieve the date of the latest row for each combination of fund, strategy and market in each calendar month. And how would i test if it is correct?
Posted
Updated 10-Jul-21 4:26am

1 solution

If you use a GROUP BY clause[^] you can partition your data into separate months.

You can then use the aggregate function MAX[^] to give you the highest date in each month.

Then it's a simple matter to use a JOIN[^] to get the row for each month that contains that date.
 
Share this answer
 
v2
Comments
johnathan indigo 10-Jul-21 10:43am    
something like this?
SELECT FundName, StrategyName, MarketName
FROM profitAndLoss
GROUP BY mtdPnlUsd
SELECT MAX(MtdPnlUsd)

thoughts on this? im stuck on the JOIN as im not sure what ill used that for?
OriginalGriff 10-Jul-21 11:39am    
My first though on this is simpel: you didn't read the link on GROUP BY well at all - that won't even run.

Go back to GROUP BY and read up on what it does and what it gives you.

It should be fairly obvious what the JOIN is for when you understand what GROUP BY does.
OriginalGriff 10-Jul-21 12:45pm    
"summary rows" is the important bit: it means that you can only return the GROUP BY row and aggregate data: SUM, AVERAGE, MAX. MIN, ...

To combine that with individual row values, you need to JOPIN those results back into the original table to "pick out" the rows you want.

This may help you understand:

SQL GROUP By and the "Column 'name' is invalid in the select list because..." error[^]
johnathan indigo 10-Jul-21 13:03pm    
do you mind writing the query and explaining through it, I am lost..
OriginalGriff 10-Jul-21 13:26pm    
Yes, I do mind - you learn nothing from it if I do! :laugh:

Give it a try: use your DB manager software (SSMS for SQL Server for example) and build just the GROUP BY query to get the top date of each month.
Then see if you can JOIN that when it works.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900