I am maintaining an inventory in azure SQL DW and want to calculate initial and final stock of a day using T-SQL. Below are the details I have - azure-sqldw

I am maintaining an inventory in azure sql DW and want to calculate initial and final stock of a day. Final stock of previous day will be initial stock for present day and Final stock for present day will be initial stock+Produced-sold. I have details of Produced and Sold quantities. How can I calculate initial and final quantities.
I am able to use lag function, but cant add the calculated value to get the finalqunatity in same query.
The query i wany to write but doestnt work is
Select lag(finalquantity,1) over ( Partition by Productid Order by Date) as Initialqty, (Initialqty+Produced-sold) as finalquantity from table
The finalquantity should come as a initialquantity for next record. I want this to happen recursively.

My answer is directly based up on the second query in the Recursive CTEs section of this answer.
I created an Inventory table as I understood your situation. I am basing my solution around InventoryDate, rather than day of week. The final item I want to mention is that your Initial stock number is coming from the Final stock number of the previous week. However, that must be defined somewhere. I hard-coded it is as the anchor member of the recursive CTE. You may pass it in as parameter or get it using a sub-query.
CREATE TABLE Inventory
(
InventoryDate DATE
, Produced INT
, Sold INT
);
INSERT INTO Inventory
(
InventoryDate
, Produced
, Sold
)
VALUES
('2020-07-20', 10, 8)
, ('2020-07-21', 9, 7)
, ('2020-07-22', 11, 10)
, ('2020-07-23', 10, 10)
, ('2020-07-24', 9, 8)
, ('2020-07-25', 7, 8)
, ('2020-07-27', 12, 14);
WITH y AS
(
SELECT
rn = ROW_NUMBER() OVER (ORDER BY InventoryDate)
, InventoryDate
, Produced
, Sold
FROM Inventory
)
, x AS
(
SELECT
CONVERT(BIGINT, 0) AS [rn]
, DATEADD(DAY, -1, MIN(InventoryDate)) AS [IventoryDate]
, NULL AS [Initial]
, NULL AS [Produced]
, NULL AS [Sold]
, 80 AS [Final]
FROM Inventory
UNION ALL
SELECT
y.rn
, y.InventoryDate
, x.Final AS [Initial]
, y.Produced
, y.Sold
, x.Final + y.Produced - y.Sold AS [Final]
FROM x
INNER JOIN y ON y.rn = x.rn + 1
)
SELECT
x.rn
, x.IventoryDate
, x.Initial
, x.Produced
, x.Sold
, x.Final
FROM x;
Here is the demo of this code.

Related

How to show not filtered data

I am new to power bi, and this question might be a common question and already answered, but I didn't find any precise solution.
I have two tables; "Dates" and "Accounts".
Dates table has only one column: "Date"(date type). It has only date value, which is day based.
Accounts table has two columns; Name(text type) and CreatedDate(date dypttype).
In my power bi model, there is a relationship(many to one, single, active) between Dates.Date and Accounts.CreatedDate columns.
I want to show account names that except the filtered ones. For example, my Accounts table look like this:
Name
CreatedDate
A Company
2020-01-01
B Company
2020-12-15
C Company
2021-03-03
D Company
2019-05-27
I have a slicer and use Dates.Date as It's field.
When I filtered my data as last 1 year (2020-08-18 - 2021-08-18), I want to show the data which is not filtered. I want to see this:
Name
CreatedDate
A Company
2020-01-01
D Company
2019-05-27
How to show the data which is not filtered?
You can create a filter Measure like following
_filter:=
SWITCH (
TRUE (),
/* t1 = what is value selected ?*/
CONVERT ( SELECTEDVALUE ( 'Calendar'[Calendar_Date] ), INTEGER ) = BLANK ()
/* t2=what is the max CreatedDate value visble in the filter context*/
/*if t1 and t2 both blank then return -999 else return t1-t2 which should be 0*/
&& CONVERT ( MAX ( tbl[CreatedDate] ), INTEGER ) = BLANK (), -999,
CONVERT ( SELECTEDVALUE ( 'Calendar'[Calendar_Date] ), INTEGER )
- CONVERT ( MAX ( tbl[CreatedDate] ), INTEGER )
)

How can I select the value of the nth row in a column in Powerbi?

I am fairly new to PowerBi,
I am trying to select the top 3 values from a table but only use specific column values. My instinct is to create a measure for each row. Here is a sample table of the data.
I've tried this but don't know enough of DAX to know how to go any further. I am able to select the top 1 value, but if I change N to 3 it doesnt work. Even if I can choose the second value instead of just the first one would help. Some sort of row index or number in an array fashion.
row[1][name]
LowestSpenders =
"The lowest spenders for the day are "
&
CALCULATE(
VALUES(Top3Low[Name]),
TOPN(1, Top3Low, Top3Low[Spent], DESC)
)
I have also tried this
LowestSpenders =
"The lowest spenders for the day are "
&
CONCATENATEX(
Top3Lost,
VALUES(Top3Lost[ClientName]),
",",
Top3Lost[LastYear],
DESC
)
I want to select the names of the people based on their positions in the table and include them in a dynamic text measure.
Something like this.
"The lowest spenders for the day are: Bob, John and Mark"
How about something like this? Rank all the names and then pick out whatever ranks you want.
LowestSpenders =
VAR Summary =
SUMMARIZE (
Top3Low,
Top3Low[Name],
"Rank", RANK.EQ ( Top3Low[Spent], Top3Low[Spent], 1 )
)
RETURN
CONCATENATEX (
FILTER ( Summary, [Rank] IN { 1, 2, 3 } ),
[Name],
", "
)
Instead of [Rank] IN { 1, 2, 3 }, you can substitute whatever criterion you want, for example, [Rank] = 2 or [Rank] > 2 && [Rank] < 5.
You're nearly there.
Use TOPN to identify the lowest n spenders, and use CONCATENATEX to iterate over this table and concatenate the names:
LowestSpenders =
CONCATENATEX (
TOPN (
3,
MyTable,
MyTable[Spent],
ASC
),
MyTable[Name],
", "
)

DAX PowerBI: Replaced blank values with zero and issue with chart

I tried to create report in Power BI with sales month by month for last 20 months, when sales is blank I want to see month with 0 value.
I decided to change Blank() values with zero adding a 0 at the end of calculation.
It works great, however I have an issue with limitaton date hierarchy, because now my chart contains a lot of months without value (first value begins in 2017, date hierarchy first value begins in 2000).
Test:=
CALCULATE (
SUM( quantity ),
flag = 1,
title = "WEEKS"
) + 0
Instead of a plain 0, you could add an IF to specify to only add that after the first value. Something like this:
Test:=
VAR FirstDate = CALCULATE ( MIN ( date ), ALL( Dates ), quantity > 0 )
RETURN
CALCULATE (
SUM( quantity ),
flag = 1,
title = "WEEKS"
) + IF( date > FirstDate, 0 )
If the condition is false, the IF returns a blank and it shouldn't show up.

How to check if current start and end dates are in previous period (start and end dates)

I have a tricky problem I am working on. I've made several attempts at capturing the data but have been unsuccessful.
I have a table in Power Bi that looks like this:
The key is in ascending order as well as the StartDate field. I would like to achieve the results in the "Period Overlap Delta" field but have had trouble trying to figure it out.
Basically, I'd like to assign a value of zero to any period (startdate-enddate combination) that is IN a previous period and take the date difference of those "super" periods.
Here is the DAX to produce the table:
Cases = DATATABLE("Key", integer, "StartDate", datetime, "EndDate", datetime
,{
{1, "01/01/2018", "01/10/2018"}
, {2, "01/03/2018","01/03/2018"}
, {3, "01/05/2018","01/07/2018"}
, {4, "01/15/2018","01/16/2018"}
, {5, "01/21/2018","01/24/2018"}
, {6, "01/25/2018", "01/27/2018"}
, {7, "01/25/2018","01/27/2018"}
})
Thanks so much in advance!!!
We need to know whether or not a certain row is overlapped by a previous row. By previous we mean the key is smaller than current row. By overlapped we mean the StartDate is earlier or equal to current row and EndDate is later or equal to current row, hence:
Overlapped =
COUNTROWS(
FILTER(
'Cases',
'Cases'[StartDate] <= EARLIER('Cases'[StartDate]) &&
'Cases'[EndDate] >= EARLIER('Cases'[EndDate]) &&
'Cases'[Key] < EARLIER('Cases'[Key])
)
)
And with this we just need to wrap it up and calculate the number of days with the DATEDIFF function:
Period Overlap Delta =
VAR Overlapped =
COUNTROWS(
FILTER(
'Cases',
'Cases'[StartDate] <= EARLIER('Cases'[StartDate]) &&
'Cases'[EndDate] >= EARLIER('Cases'[EndDate]) &&
'Cases'[Key] < EARLIER('Cases'[Key])
)
)
RETURN
IF(Overlapped, 0, DATEDIFF('Cases'[StartDate], 'Cases'[EndDate], DAY) + 1)
P.S. The use of DATATABLE to provide sample data is golden and should be promoted more often!

PowerBI Getting ERROR A function 'CALCULATE' has been used

I would like to show the card values:
if current month value is not available then it should compare with the previous month value automatically.
Like
In above image Apr-2017 value is not available then it should compare with the Mar-2017 value.
If Mar-2017 value also not available then the previous month value.Keep on goes.
And one more thing is I don't want to use the slicer anymore. Actually I am not going to use the slicer.
I just want to show the month comparison value in a card visuals.
I would like to give info of what kind of data that I have. I have table's plan rev, actual rev, and MonthYear
I have created a relationship using Date column from MonthYear table to plan rev and actual rev Date columns.
MonthYear table
And in plan rev, month year, plan rev, date, and in actual rev actual rev, month year, and date columns.
Then written measures for
For Sumof Plan rev-->
PlanSum = SUM('Revenue Report'[Planned Rev])
For Prev month value-->
PlanPrevMon = CALCULATE([PlanSum],PREVIOUSMONTH('Month Year'[Date]))
For Start and End Date of the months
FILTERDATESTART= FIRSTDATE('MonthYear'[Date])
FILTERDATEEND= LASTDATE('MonthYear'[Date])
Then for current month PlanArrows measure is.
PlanArrows = CALCULATE(
IF(
ISBLANK([PlanSum]),"No data Available",[PlanSum]
)& " "& IF(
[PlanSum]=[PlanPrevMon],
"",
IF([PlanSum]>[PlanPrevMon],
UNICHAR(8679),
UNICHAR(8681)
) & IF([PlanSum]<=0,
"",""
)
),
'Month Year'[Date]>=FILTERDATESTART,
'Month Year'[Date]<=FILTERDATEEND
)
But it is not working. I'm getting an error:
A function 'CALCULATE' has been used in a True/False expression that is used as a table filter expression. This is not allowed.
Any Suggestions please,
Thanks
Mohan V
I think i got the solution on my own.
I have written measure which solved this issue.
PlanArrows =
VAR s = [FILTERDATESTART]
VAR e = [FILTERDATEEND]
RETURN
CALCULATE (
IF ( ISBLANK ( [PlanSum] ), "No data Available", [PlanSum] ) & " "
& IF (
[PlanSum] = [PlanPrevMon],
"",
IF ( [PlanSum] > [PlanPrevMon], UNICHAR(8679), UNICHAR(8681) )
& IF ( [PlanSum] <= 0, "", "" )
),
'Month Year'[Date] >= s
&& 'Month Year'[Date] <= e
)