how to calculate the turnover in powerbi - sql-server

I want to create a report in power Bi that shows the turnover for each year but in my database a turnover can not be equal to the total amount of the bills because there can be assets to be deducted. so in my database there is operation_code table which contains a SENS column this column indicates if this operation is either input or output and the turnover will be calculated as follows: if (CODE_OP.SENS = output), + sum (ENT.HTMT / ENT .DEVP) else if (CODE_OP.SENS = input), - sum (ENT.HTMT / ENT.DEVP)
i did a test with SQL Statements :
SELECT YEAR(ENT.PIDT) ,T020.SENS,
CASE
WHEN T020.SENS= 2 THEN
sum (ENT.HTMT / ENT.DEVP)
WHEN T020.SENS = 1 THEN -1 * sum (ENT.HTMT / ENT.DEVP)
END as CA FROM ENT
left join T020 on
T020.OP = ENT.OP
WHERE ENT.PICOD=4 AND ENT.TICOD='C' AND ENT.DOS=998
GROUP BY YEAR(ENT.PIDT)--,T020.SENS
but when i try to do it in power BI Using DAX by creating a measure
Measure =
Switch ( True();
ALL(T020[SENS])=2,0;SUM(ENT[HTMT])/SUM(ENT[DEVP]) ;
ALL(T020[SENS])=1,0; SUM(ENT[HTMT])/(SUM(ENT[DEVP]))
)
an error appear when i try to use the measure that it is impossible to display the visual element . enter image description here

The following DAX should do the trick:
Measure =
CALCULATE(
SUMX(ENT, DIVIDE(ENT[HTMT], ENT[DEVP])),
T020[SENS] = 2
)
- CALCULATE(
SUMX(ENT, DIVIDE(ENT[HTMT], ENT[DEVP])),
T020[SENS] = 1
)

Related

POWER BI - workaround possible for recursive calculation of my dax measure?

I have 2 tables on orders with the order validity date and in transit stock (stock reaching where the order will be serviced).
(using sample data to simplify for understanding)
I am looking for a final calculation like this in my final table -
have done the calculation till column 4 in power BI
if this was in excel i could have simply done
used_stock(2) = serviced(1) + used_stock(1)
avail_stock(2) = total_qty(2) - used_stock(2)
serviced(2) = min(order(2),avail_stock(2))
My base tables look like this - 
order table -
intransit table -
I have done the total_qty measure calculation by finding the cumulative sum of shipment quantity for the dates before selected value of order validity date.
I am trying to do the rest of the measures but ending up in circular references. Is there a way I can do it?
edit -
Clarifying it a bit more for the logic needed -
let's say the 2nd order is 15 and the 2nd shipment reaches on 24th, then the base data and output table should look like this -
With present proposed solution the table will erroneously look like -
Try with these below measures-
total_qty =
VAR current_row_date = MIN('order'[order valid till date])
RETURN
CALCULATE(
SUM(intrasit[quantity in shipment]),
FILTER(
ALL(intrasit),
intrasit[expected date of reaching] < current_row_date
)
)
used_stock =
VAR current_row_date = MIN('order'[order valid till date])
RETURN
CALCULATE(
SUM('order'[order quantity]),
FILTER(
ALL('order'),
'order'[order valid till date] < current_row_date
)
) + 0
avail_stock = [total_qty] - [used_stock]
serviced =
IF(
MIN('order'[order quantity]) <= [avail_stock],
MIN('order'[order quantity]),
[avail_stock]
)
Here is your final output-

SQL Subquery with a COUNT

I have a table of our communications containing; Created User, Created Date & Sub Code. I want the output to have 4 columns in SSRS, showing communications from the previous month;
Comms logged Dealt With % Dealt With
Created User 1
Created User 2
So far I've got;
SELECT
[EM-COMMUNICATION].[CRT-USER]
,COUNT([EM-COMMUNICATION].[CRT-USER]) AS LOGGED
,(SELECT COUNT([EM-COMMUNICATION].[CRT-USER]) FROM [EM-COMMUNICATION] WHERE [EM-COMMUNICATION].[SUB-CODE] = N'DEALTWITH' AND DateDiff(MONTH,[EM-COMMUNICATION].[CRT-DATE],GetDate()) = 1) AS Dealt
FROM
[EM-COMMUNICATION]
WHERE
DateDiff(MONTH,[EM-COMMUNICATION].[CRT-DATE],GetDate()) = 1
GROUP BY
[EM-COMMUNICATION].[CRT-USER]
The problem I'm having is that the sub query is returning a count of comms for all users, instead of matching the groupings of the main query, i.e., each row has the same count in 'Dealt With'
You need to relate your subquery with your main query using AND [EM-COMMUNICATION].[CRT-USER] = T.[CRT-USER]
SELECT
[EM-COMMUNICATION].[CRT-USER]
,COUNT([EM-COMMUNICATION].[CRT-USER]) AS LOGGED
,(SELECT COUNT([EM-COMMUNICATION].[CRT-USER]) FROM [EM-COMMUNICATION] as T WHERE T.[SUB-CODE] = N'DEALTWITH' AND DateDiff(MONTH,T.[CRT-DATE],GetDate()) = 1 AND [EM-COMMUNICATION].[CRT-USER] = T.[CRT-USER]) AS Dealt
FROM
[EM-COMMUNICATION]
WHERE
DateDiff(MONTH,[EM-COMMUNICATION].[CRT-DATE],GetDate()) = 1
GROUP BY
[EM-COMMUNICATION].[CRT-USER]

SQL Server : Sum function is returning wrong value

So this is my query
select a.ERSDataValues_ERSCommodity_ID,c.ersGeographyDimension_country,
b.ERSTimeDimension_Year,
sum(a.ERSDataValues_AttributeValue) as Total
from cosd.ERSDataValues a ,cosd.ERSTimeDimension_LU
b,cosd.ERSGeographyDimension_LU c
where a.ERSDataValues_ERSCommodity_ID in (SELECT
ERSBusinessLogic_InputDataSeries
FROM [AnimalProductsCoSD].[CoSD].[ERSBusinessLogic]
where ERSBusinessLogic_InputGeographyDimensionID = 7493
and ERSBusinessLogic_InputTimeDimensionValue = 'all months'
and ERSBusinessLogic_Type = 'time aggregate')
and a.ERSDataValues_ERSTimeDimension_ID = b.ERSTimeDimension_ID
and c.ersGeographyDimension_country != 'WORLD'
and a.ERSDataValues_ERSGeography_ID=c.ERSGeographyDimension_ID
group by b.ERSTimeDimension_Year,a.ERSDataValues_ERSCommodity_ID,
c.ersGeographyDimension_country
order by b.ERSTimeDimension_Year,a.ERSDataValues_ERSCommodity_ID
This is the updated query, I know it is long but I am facing the same issue the sum does not match with values when I sum up manually
It's most likely a problem with your JOINs (which you aren't technically using). Try removing the SUM and GROUP functions and see if you're getting duplicate rows (maybe limit your time frame to get fewer rows if this is a large data set):
SELECT b.TimeDimension_Year ,
c.GeographyDimension_country ,
a.DataValues_AttributeValue
FROM cosd.DataValues a ,
cosd.TimeDimension_LU b ,
cosd.GeographyDimension_LU c
WHERE a.DataValues_Commodity_ID = 2257
AND a.DataValues_TimeDimension_ID = b.TimeDimension_ID
AND c.GeographyDimension_ID = 7493
AND b.TimeDimension_Year = 2015;

MDX Percentage Row Not Calculating Correctly

I am trying to calculate a percentage row in a table based on a total column derived earlier in the query.
There are two columns then I create a total for that column. In the next row I want a percentage of the total to show. The output should be something like:
Life Non-Life (P&C) SumTotal
Premiums 66,104.44 916,792.51 982,896.95
Percentage 6.73% 93.27% 1
But instead the second line shows zero.
How do I structure the query to calculate correctly?
Here is the mdx code:
with member [LocationSpecificClass].[Hierarchy].[All].&[Insurance Market Statistics].[SumTotal] as SUM([LocationSpecificClass].[Hierarchy].[All].&[Insurance Market Statistics] , [Measures].[Value] )
member [LocationSpecificData].[Data Type].[All].[Percentage] as [LocationSpecificData].[Data Type].[All].[Gross Written Premiums Total - Calculated], [Measures].[Value] ) / ([LocationSpecificClass].[Hierarchy].[All].&[Insurance Market Statistics].[SumTotal], [Measures].[Value] )
Select { [LocationSpecificClass].[Hierarchy].[All].&[Insurance Market Statistics].&[Life], [LocationSpecificClass].[Hierarchy].[All].&[Insurance Market Statistics].&[Non-Life (P&C)], [LocationSpecificClass].[Hierarchy].[All].&[Insurance Market Statistics].[SumTotal] } On Columns ,
{ [LocationSpecificData].[Data Type].[All].[Gross Written Premiums Total - Calculated] , [LocationSpecificData].[Data Type].[All].[Percentage] } On Rows
FROM [CubeDatabase]
Please try the following example, which worked fine in my environment. I've used our date dimension [Datum] with the year attribute [Jahr] to add a second a line by adding [Line2]. The first shown line is the year 2016. Set the calculated measures [M1] and [M2] to your needs and exchange the year dimension accordingly.
WITH
MEMBER [Measures].[M1] AS [Measures].[name of your measure for col 1]
MEMBER [Measures].[M2] AS [Measures].[name of your measure for col 2]
MEMBER [Measures].[Total] AS [Measures].[M1] + [Measures].[M2]
MEMBER [Datum].[Jahr].[Line2] AS
Divide(
([Datum].[Jahr].&[2016], [Measures].CurrentMember),
([Datum].[Jahr].&[2016], [Measures].[Total])
)
SELECT {
[Measures].[M1],
[Measures].[M2],
[Measures].[Total]
} ON 0,
{
[Datum].[Jahr].&[2016],
[Datum].[Jahr].[Line2]
} ON 1
FROM [name of cube]
The result in my environment looks like this:

Get random result from JPQL query over large table

I'm currently using JPQL queries to retrieve information from a database. The purpose of the project is testing a sample environments through randomness with different elements so I need the queries to retrieve random single results all through the project.
I am facing that JPQL does not implement a proper function for random retrieval and postcalculation of random takes too long (14 seconds for the attached function to return a random result)
public Player getRandomActivePlayerWithTransactions(){
List<Player> randomPlayers = entityManager.createQuery("SELECT pw.playerId FROM PlayerWallet pw JOIN pw.playerId p"
+ " JOIN p.gameAccountCollection ga JOIN ga.iDAccountStatus acs"
+ " WHERE (SELECT count(col.playerWalletTransactionId) FROM pw.playerWalletTransactionCollection col) > 0 AND acs.code = :status")
.setParameter("status", "ACTIVATED")
.getResultList();
return randomPlayers.get(random.nextInt(randomPlayers.size()));
}
As ORDER BY NEWID() is not allowed because of JPQL restrictions I have tested the following inline conditions, all of them returned with syntax error on compilation.
WHERE (ABS(CAST((BINARY_CHECKSUM(*) * RAND()) as int)) % 100) < 10
WHERE Rnd % 100 < 10
FROM TABLESAMPLE(10 PERCENT)
Have you consider to generate a random number and skip to that result?
I mean something like this:
String q = "SELECT COUNT(*) FROM Player p";
Query query=entityManager.createQuery(q);
Number countResult=(Number) query.getSingleResult();
int random = Math.random()*countResult.intValue();
List<Player> randomPlayers = entityManager.createQuery("SELECT pw.playerId FROM PlayerWallet pw JOIN pw.playerId p"
+ " JOIN p.gameAccountCollection ga JOIN ga.iDAccountStatus acs"
+ " WHERE (SELECT count(col.playerWalletTransactionId) FROM pw.playerWalletTransactionCollection col) > 0 AND acs.code = :status")
.setParameter("status", "ACTIVATED")
.setFirstResult(random)
.setMaxResults(1)
.getSingleResult();
I have figured it out. When retrieving the player I was also retrieving other unused related entity and all the entities related with that one and so one.
After adding fetch=FetchType.LAZY (don't fetch entity until required) to the problematic relation the performance of the query has increased dramatically.

Resources