i am looking to get the date diff from two or more row in a way that first rows serviceto date - second rows service start date so that i can get diff - amazon-web-services

my data looks like this
userid
completedat
serviceperiodfrom
serviceperiodto
00002cd9-94eb-4c06-a2c4-75253fd541b9
2020-11-25T14:20:04.293Z
2020-11-25T14:20:04.200Z
2021-02-25T14:20:04.200Z
00002cd9-94eb-4c06-a2c4-75253fd541b9
2021-03-21T10:27:34.842Z
2021-03-21T10:27:34.800Z
2022-03-21T10:27:34.800Z
00002cd9-94eb-4c06-a2c4-75253fd541b9
2020-07-24T11:22:12.410Z
2020-07-24T11:22:12.300Z
2020-10-24T11:22:12.300Z
I need the date diff from serviceperiodto date of first row - serviceperiodfrom date of secondrow and it goes for as many iteration as it has these details for each userid
please help me i tried joining the tables using subqueries tried to create a pivot table but none of them seem working for me please help

You can use lag/lead to access previous/next item:
WITH dataset
AS (SELECT *
FROM
(
VALUES
(1, from_iso8601_timestamp('2020-11-25T14:20:04.200Z'), from_iso8601_timestamp('2021-02-25T14:20:04.200Z')),
(1, from_iso8601_timestamp('2021-03-21T10:27:34.800Z'), from_iso8601_timestamp('2022-03-21T10:27:34.800Z')),
(1, from_iso8601_timestamp('2020-07-24T11:22:12.300Z'), from_iso8601_timestamp('2020-10-24T11:22:12.300Z'))
) AS t (userid, serviceperiodfrom, serviceperiodto)
)
SELECT date_diff(
'hour',
serviceperiodto,
lead(serviceperiodfrom, 1) OVER (PARTITION BY userid ORDER BY serviceperiodfrom))
FROM dataset
Output:
_col0
770
572
 

Related

Add previous month column DAX Power BI

I have a fact table which has 'Last Data Update' column that shows current month date(mm/dd/yyyy), 06/13/2022.
I am trying to add column called 'report month' that returns a value that shows previous month/year 05/2022 to create relationship with calendar table.
=Date.Month([Last Data Update])-1
I have used this code, but this only returns 5 and it is in number format.
is there a way to return 05/2022 in DAX ?
Thanks in advance.
This is M, not DAX. Replace your custom column with the following code:
Text.PadStart( Text.From(Date.Month([Last Data Update])-1),2,"0") &"/"& Text.From(Date.Year([Last Data Update]))
It worked for we with this 3 simple steps:
Step 1: Create a column with current year (True/False statement) by using:
CurrentYear = IF(YEAR([Last Data Update])=YEAR(NOW()),1,0)
Step 2: Create a column that will indicate if the current date (based on column "Last Data Update") belongs to previous month or not (True/False statement).
PreviousMonth = IF([CurrentYear]=1 && (MONTH(TODAY())-1)=MONTH([Last Data Update]),1,0)
Step 3: Create a filter on your visual where you select filter "PreviousMonth" with value "1" to show dates only from previous month).
If you like it. Don't forget to rate it.
Success,
Mark
This month-year
FORMAT( [Last Data Update], "mm/yyyy")
previous month
FORMAT( DATEADD([Last Data Update],-1,Month), "mm/yyyy")

Pivot with dynamic DATE columns

I have a query that I created from a table.
example:
select
pkey,
trunc (createdformat) business_date,
regexp_substr (statistics, 'business_ \ w *') business_statistics
from business_data
where statistics like '% business_%'
group by regexp_substr(statistics, 'business_\w*'), trunc(createdformat)
This works great thanks to your help.
Now I want to show that in a crosstab / pivot.
That means in the first column are the "business_statistics", the column headings are the "dynamic days from business_date".
I've tried the following, but it doesn't quite work yet
SELECT *
FROM (
select
pkey,
trunc(createdformat) business_date,
regexp_substr(statistics, 'business_\w*') business_statistics
from business_data
where statistics like '%business_%'
)
PIVOT(
count(pkey)
FOR business_date
IN ('17.06.2020','18.06.2020')
)
ORDER BY business_statistics
If I specify the date, like here 17.06.2020 and 18.06.2020 it works. 3 columns (Business_Statistic, 17.06.2020, 18.06.2020). But from column 2 it should be dynamic. That means he should show me the days (date) that are also included in the query / table. So that is the result of X columns (Business_Statistics, Date1, Date2, Date3, Date4, ....). Dynamic based on the table data.
For example, this does not work:
...
IN (SELECT DISTINCT trunc(createdformat) FROM BUSINESS_DATA WHERE statistics like '%business_%' order by trunc(createdformat))
...
The pivot clause doesn't work with dynamic values.
But there are some workarounds discuss here: How to Convert Rows to Columns and Back Again with SQL (Aka PIVOT and UNPIVOT)
You may find one workaround that suits your requirements.
Unfortunately, I am not very familiar with PL / SQL. But could I still process the start date and the end date of the user for the query?
For example, the user enters the APEX environment as StartDate: June 17, 2020 and as EndDate: June 20, 2020.
Then the daily difference is calculated in the PL / SQL query, then a variable is filled with the value of the entered period using Loop.
Example: (Just an idea, I'm not that fit in PL / SQL yet)
DECLARE
startdate := :P9999_StartDate 'Example 17.06.2020
enddate := P9999_EndDate 'Example 20.06.2020
BEGIN
LOOP 'From the startdate to the enddate day
businessdate := businessdate .... 'Example: 17.06.2020,18.06.2020,19.06.2020, ...
END LOOP
SELECT *
FROM (
select
pkey,
trunc(createdformat) business_date,
regexp_substr(statistics, 'business_\w*') business_statistics
from business_data
where statistics like '%business_%'
)
PIVOT(
count(pkey)
FOR business_date
IN (businessdate)
)
ORDER BY business_statistics
END;
That would be my idea, but I fail to implement it. Is that possible? I hope you understand what I mean

New column indicating if row is the first instance of the value for the Entity ID in PowerQuery Editor

I currently have a column that is created using the following DAX formula which indicates if the listed activity is the first one ever for that Entity ID:
First Time Activity =
if('Activity Table'[Timestamp]=
CALCULATE(min('Activity Table'[Timestamp]),
filter('Activity Table',
'Activity Table'[Entity ID] = earlier('Activity Table'[Entity ID]) &&
'Activity Table'[Activity Name] = earlier('Activity Table'[Activity Name])
)
)
,1,BLANK())
But I need this now to be a column made in PowerQuery instead of DAX. Any help on the PowerQuery formula would be much appreciated.
Thanks
In the query editor, you can do the following steps:
Group by ID and Activity taking the min over the Date column as its aggregation.
Merge that grouped table back onto the original table (matching on ID and Activity and using left outer join).
Expand the min date column.
On the merged and expanded table, replace non-nulls in the expanded column with 1.

Dax Finding date based on Criteria calculated Column

I couldn't find an answer for my issue elsewhere, so trying my luck here.
I have sales table and my final result should determine if there were sales made for same person in specific period of time, for example within 7 business days. for example:
For ID 123 I have to flag it that sale for products A,B,C where within specified period.
For ID 1234 only sales of products A and B meet the criteria product C was sold in irrelevant time frame.
I've created a date table with indicators that determine for each date if the date is a working day, but i am struggling to calculate the relevant last working day
For example: I need that for 01/01/2019 i will get 10/01/2019 date, based on NUMOFDAYS and FinalWorkday = TRUE, which basically means that i have to count NUMOFDAYS times TRUE statement for each date and return corresponding date.
After that step done I think that it would be pretty easy for me to determine if the sale for a person was made in specific time frame.
If someone can give me direction for that much appreciated
Thank you in advance
You could use a DateTable like this one:
I used the following DAX-expressions for the calculated columns:
nrDays = 7
isWorkDay = WEEKDAY('DateTable'[Date],2) < 6
rankWorkingDays = RANKX ( FILTER ( DateTable, DateTable[isWorkDay] = TRUE () ),
DateTable[Date] , , ASC )
LastWorkDay = LOOKUPVALUE ( DateTable[Date],
DateTable[isWorkDay], TRUE (),
DateTable[rankWorkingDays], DateTable[rankWorkingDays] + DateTable[nrDays])
This issue can be solved by the following, since three are non-working days/holidays we can filter them out via POWERQUERY, than add an Index Column and Another column Which is basically Index column + Number of days wanted, then simply merge duplicate of dates query on Index+number of days wanted column on Index column. And we get the correct date

Split single row of data in Power BI data source into multiple rows

I have a table in a Power BI data source with a column for term start and term end date (term length can be longer than a month), along with meta data on the term. I need to report on status of purchased terms as at the end of each month. As far as I can see, the best way of accomplishing this would be to create a calculated table with an entry for each month on which a term is active at its end.
For example, an entry in the original table with the following data:
TermStartDate TermEndDate PurchaseAmount
2018-01-03 2018-04-12 100
Would end up in the calculated table as follows:
MonthPurchased PurchaseAmount
2018-01 100
2018-02 100
2018-03 100
How to accomplish this? Is there a better way than creating a separate calculated table to get this data? Any help or advise is appreciated
I managed to solve this myself, I detail the required steps below for reference:
Change start and end date column data types from Datetime to Date. <- This is needed to ensure we only generate dates on day boundaries in the next step
Add custom column with the following formula:
Month = List.Select( List.Dates([TermStartDate], Number.From([TermEndDate] - [TermStartDate]) +1, #duration(1, 0, 0, 0)), each _ = Date.EndOfMonth(_) )
This generates a list of dates between start and end, then filters to only leave the dates that are at the end of a month
Expand to new rows on the new Month column (menu at the top of the column)
Use Detect Data Type option on the Month column to change the datatype from Any to Date (for some reason I cannot manually select Date, the DataType menu option is greyed out on the Month column)