SSAS 2012 DAX SamePeriodLastYear() with Date Dimension - sql-server

I have a date dimension and a fact table. I have two measures:
WorkOrdersCount:=
count(
FactWorkOrderLifeCycle[Clientsid]
)
and
WorkOrdersLastYearCount:=
CALCULATE(
count(FactWorkOrderLifeCycle[Clientsid]),
SAMEPERIODLASTYEAR(DimDate[FullDate])
)
WorkOrdersCount is simple and works fine. I thought WorkOrdersLastYearCount would be simple as well, but I now realize I don't understand SAMEPERIODLASTYEAR().
My date dimension has a DateSID column containing an integer representation of date as YYYYMMDD. It has two recordkeeping rows with SIDs of -1 and -2 for unknown and TBD dates. I'm only using the -1 row in this solution. The data is stored in a SQL Server table and the FullDate column is a "date" type. The actual value is 1900-01-01.
My fact, FactWorkOrderLifecycle, has a field called InvoicedDateSID that can have a null value which I replace with -1.
No errors are thrown in Visual Studio or when processing the olap, but upon referencing the column in a pivot table I get the following error:
ERROR - CALCULATION ABORTED: Calculation error in measure
'FactWorkOrderLifeCycle'[WorkOrdersLastYearCount]: An invalid numeric
representation of a date value was encountered.
Things I've tried (not all make sense):
changed SID values to positive integers
changed date value in dimdate to 9999-12-31 instead of 1900-01-01 when I saw that DAX dates might start at 1900-03-01
adding other dimensions to the pivot first to see if the formula calculates correctly at all.
I'm a DAX noob and I'm not sure how to troubleshoot this. Any help is appreciated!

Make sure you calendar table is indeed using a Date data type.
Remove any time component of your dates.
Make sure there are no gaps and no duplicates in your Calendar table.
Make sure you are using fields from your Calendar table on the pivot, and NOT date related fields from your data table.

Related

Data Studio - Grouping by Week

I have a simple Data Studio table consisting of two columns. The first column is the week (ISO Year Week) and the second column is the total registrations we've received for that week.
However, my Week column repeats 7 times (7 Rows) for each week as it's counting by day within that week. See below:
Is there any way to get this to group by the listed week? Below are my settings:
Dimension = Conversion Date set as "ISO Year Week" for the type.
Metric = Equals the count of Conversion Date (Same Conversion Date field used for dimension)
Any help would be much appreciated.
There might be an issue with the date format of the source. Without knowing the source (e.g. Google Analytics or Sheets) it’s hard to tell.
Blended Data
I recently had this issue with blended data. The response of a similar question helped me to find a way.
Basically you have to add a new custom field to the data source with the formula WEEK(date_field_link). Data studio will recognise this as a date in compatibility mode, but for me it still works. Then you can use this new date field as a join key to blend the data while grouping it in weeks.
Normal Data
If this problem appears in a regular non-blended dataset you might want to check if Data Studio correctly catches the date as a date. This help article from Google might be worth checking out: https://support.google.com/datastudio/answer/6401549?hl=en#zippy=%2Cin-this-article
I made a similar case work using blended data.
Your column "Conversion Date" repeats the same week 7 times because it's just a display value. Every row has a date value (year, month and a day) but you're just showing the corresponding week. So, data-studio treats them as different data and doesn't group them.
To be able to group them by Week you need to create a new field with a value containing only the week and the year. So, you can use the formula
YEARWEEK(your_date)
The resulting Date will be groupable.
NB1: If your date isn't of the type Date, you can parse it from text to date using
the method:
PARSE_DATE("%Y-%m-%d", your_date_text)
NB2: If the created field has the type number and doesn't show the possibility to change type to Date, you can do this trick: (it's weird but it works):
First type as a formula for the created field and apply:
MONTH(your_date)
This will unlock the compatibility Date types. You can choose from them the ISO Year Week type.
and then change the formula from MONTH(your_date) to YEARWEEK(your_date) [your formula] as I explained above. The chosen date type won't go away even if it wasn't available the first time.

Extract data by day from SQL Server

I need to get all the values from a SQL Server database by day (24 hours). I have timestamps column in TestAllData table and I want to select the data which only corresponds to a specific day.
For instance, there are timestamps of DateTime type like '2019-03-19 12:26:03.002', '2019-03-19 17:31:09.024' and '2019-04-10 14:45:12.015' so I want to load the data for the day 2019-03-19 and separately for the day 2019-04-10. Basically, it is needed to get DateTime values with the same date.
Is this possible to use some functions like DatePart or DateDiff for that?
And how can I solve such problem overall?
As in this case, I do not know the exact difference in hours between a timestamp and the end of the day (because there are various timestamps for 1 day) and I need to extract the day itself from the timestamp. After that, I need to group the data by days or something like this and get block by block. For example:
'2019-03-19' - 1200 records
'2019-04-10' - 3500 records
'2019-05-12' - 10000 records and so on
I'm looking for a more generic solution not supplying a timestamp (like '2019-03-19') as a boundary or in a where clause because the problem is not about simply filtering the data by some date!!
UPDATE: In my dataset, I have about 1,000,000 records and more than 100 unique dates. I was thinking about extracting the set of unique dates and then kind of run a query in the loop where the data would be filtered by the provided day. It would look in such a way:
select * from TestAllData where dayColumn = '2019-03-19'
select * from TestAllData where dayColumn = '2019-04-10'
select * from TestAllData where dayColumn = '2019-05-12'
...
I might use this query in my code, so I may run it in the loop from Scala function. However, I am not sure that in terms of performance it would be ok to run separate unique dates extraction query.
Depending on whether you want to be able to work with all the dates (rather than just a subset), one of the easiest ways to achieve this is with a cast:
;with cte as (SELECT cast(my_datetime as date) as my_date, * from TestAllData)
SELECT * FROM cte where my_date = '2019-02-14'
Note when casting datetime to date, times are truncated, ie just the date part is extracted.
As I say though, whether this is efficient, depends on your needs, as all datetime values from all records will be cast to date, before the data is filtered. If you want to select several dates (as opposed to just one or two), however, it may prove overall quicker, as it reads the whole table once and then gives you a column upon which you can much more efficiently filter.
If this is a permanent requirement, though, I would probably use a persisted computed column, which effectively would mean that the casting is done once initially and then only again if the corresponding value changed. For a large table I would also strongly consider an index on the computed column.

SSRS report - export to excel date time filteration

Populating an SSRS report from dyanmic dataset i.e. number column and order of columns may vary based on condition, and this report on trying to export to excel. But in exporting date column filtration not working. Finds the reason is I bind the column in string format.
Sample data format to understand. Here the columns & order of columns may vary as per condition.
And I am converting this to below format and passing to SSRS as dataset.
And populating report by grouping with ROW_NO & COL
Then I tried to convert DOB column to date time.
For converting DOB to date format changed return type of DOB from sql query as datetime, converted column value to date time using CDate() in SSRS and formatted in own format (dd-mmm-yyyy).
Below expression used for converting to date time:
IIF((Fields!COL.Value="DOB") ,CDate(Fields!VALUE.Value),(Fields!VALUE.Value))
But showing #Error for columns data type other than date time:
Go to your detail textbox in the DOB column. And use the following expression:
=Format(CDate(Fields!DOBValue.Value), "dd-MM-yyyy")
This way the date in your DOB column will show 23-01-2018
Note: The expression just works if in the Fields!DOBValue.Value field are just dates. If there is a N/A it will throw an error. Then you have to clear the N/A first.
And if you want to export it to Excel you need to set the language in your report properties (use your region) and go to your textbox where you wrote in the above expression under Textbox properties > Number chose Date format.
UPDATE
Based on your updated question I think I found the error. The problem is your writing of the month names combined with the report language. My report language is set to DE. For me the following works:
=CDate("15-Mai-94") 'Result 05.05.1994
But this dosent work:
=CDate("15-May-94") 'Result =Error
The second one works, when I set the report language to EN but then the first one throws an error

Max aggregate function with autonumber and date field in access

I have ran into a problem recently. One of the tables I have in MS Access database contains multiple fields but the main focus is on an autonumber field and date field. When I try to apply Select query with Max(autonumber) function and where clause containing date field, the wrong value or rather empty column is shown. as soon as i remove the date field from the where clause, the value is returned fine. My query is attached. Any help would be appreciated.
SELECT MAX(serial) AS Expr1
FROM coaDetails
WHERE (((coaDetails.[title])='CLAIMS')AND ((coaDetails.[dates])=#04/08/2018#));
The above query, serial is autonumber while dates is date/time with format as dd/mm/yyyy
There is no error in the query but it just gives wrong value. as soon as date condition is removed it gives results.
Use the mm/dd/yyyy or yyyy/mm/dd format for the string expression for the date value:
WHERE (((coaDetails.[title])='CLAIMS')AND ((coaDetails.[dates])=#2018/08/04#));
In the SQL code, the dates have to be formatted the american way: #mm/dd/yyyy#. In the query design grid, which is a user-friendly, graphical view of the SQL code in the back, the format depends on your regional settings.
Therefore, just use the month first:
SELECT MAX(serial) AS Expr1
FROM coaDetails
WHERE (((coaDetails.[title])='CLAIMS')AND ((coaDetails.[dates])=#08/04/2018#));

display image on a report based on two date

I am using sql server 2005 reporting service to generate report base on a database. There are two columns which are datetime type ColumnA and ColumnB. The report would display a KPI image on this report by comparing these two columns.Below is the expression for selecting image
SWITCH(DateDiff("d",Fields!ColumnA.Value,Fields!ColumnB.Value)<0,"kpi_r",
DateDiff("d",Fields!ColumnA.Value,Fields!ColumnB.Value)>0,"kpi_g",
DateDiff("d",Fields!ColumnA.Value,Fields!ColumnB.Value)=0,"kpi_y")
For most of the records, the image is correct. Only for one record, the result is very strange.
For this record
ColumnA=2010-04-23 08:00:00 ColumnB=2010-04-22 17:00:00
It would display kpi_r, it displayed kpi_y. I have checked the value of DateDiff(d,Fields!ColumnA.Value,Fields!ColumnB.Value) in the SSMS, the value is -1. Why does it display kpi_y? Does anyone meet this problem before?
Best Regards,
The difference is that the SSMS DATEDIFF function counts the interval boundaries between the two dates whereas ReportBuilder counts the actual intervals. Within SSMS if you cross midnight you have triggered a day boundary so in your example you get -1. In ReportBuilder it is looking for 24 hours to be between the two values so you get 0. If you change the time on ColumnA to be '2010-04-23 17:00:00' you will see the value changes to -1 as you expected. For your comparison it would probably make sense to strip the time component from ColumnA and ColumnB when you do this SWITCH statement.
the above answer is spot on.
here's a few ways to strip time off a date depending on your preferences:
1. do it in RS: use and expression like dateserial(year(Fields!ColumnA.Value),month(Fields!ColumnA.Value), day(Fields!ColumnA.Value)) in your switch expression
2. do it in SQL: use an expression like cast(round(cast(ColumnA as float),0,1) as datetime) in your query

Resources