As Maciej Los said - you have too many subqueries.
The thing is almost impossible to read. Use some whitespace (linefeeds) to format it so you can read it.
If you do that you will realise that you are calculating
Expr7
twice (the first two sections of your query)
Your query boils down to
Expr7 / Expr7 + Expr3 + Expr4 * 100.0
That is not how to calculate a percentage! Note that
Expr7 / Expr7
equals 1!
You also need to use brackets properly as that is actually calculated as
1 + Expr3 + (Expr4 * 100.0)
I have no idea where
SS.[ID]
is being sourced from.
Other things to note - if you are only selecting from a single table, or if the column name is unique across joined tables, then you don't need to use the table name as a qualifier i.e. use
EndTotal
instead of
VInvoices.EndTotal
.
You can give tables ALIASES e.g.
FROM AccountsDefinition AD
INNER JOIN Directexpenses DE
Both of these points will make your code easier to read
I suggest you throw this query away and start again.
To express A as a percentage of B the formula is
(A / B) * 100.0
Use some variables e.g.
DECLARE @Expr7 numeric (15,2)
DECLARE @Expr3 numeric (15,2)
DECLARE @Expr4 numeric (15,2)
DECLARE @SSID int = (SELECT MAX([ID]) FROM somewhere)
Then calculate each part separately for now.
I'm guessing you want something like this
SET @Expr7 = (SELECT SUM(ISNULL([TotalContractorValue],0))
FROM ClientExtractALLInfoReportView
WHERE [OPID] = @SSID)
SET @Expr3 = (SELECT SUM(ISNULL([EndTotal],0))
FROM VInvoices
WHERE [OPID] = @SSID)
SET @Expr4 = (SELECT SUM(ISNULL(AZ.[KhaznaTotal],0))
FROM AzenSarfKhazna AZ
WHERE AZ.[OPID] = @SSID
AND AZ.[Type] = 'Other'
AND AZ.[TypeID] IN (
SELECT AD.[ID]
FROM AccountsDefinition AD
INNER JOIN Directexpenses DE
ON AD.[HaveFather] = DE.[DEXID]
)
DECLARE @prec numeric(15,2) = 100.0 * @Expr7 / (@Expr3 + @Expr4)
But note - this is just a guess at the final format as you have not given us any information about what data is in what table. I'm also not entirely sure why you have a join to DirectExpenses as you don't appear to be filtering on any columns from it
When you've got that working it might be easier to see where you could use table joins etc to refactor the query. But for now that should at least get you the numbers you want.