0% found this document useful (0 votes)
77 views

Cognos RS - Functions - 13

The document discusses various date and time functions that can be used to manipulate timestamps and perform time-related calculations in relational and dimensional contexts. It provides examples of functions to truncate timestamps, make timestamps from date keys, get the last day of the month, and filter for periods like year-to-date, quarter-to-date, and trailing months.

Uploaded by

Harry Konnect
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

Cognos RS - Functions - 13

The document discusses various date and time functions that can be used to manipulate timestamps and perform time-related calculations in relational and dimensional contexts. It provides examples of functions to truncate timestamps, make timestamps from date keys, get the last day of the month, and filter for periods like year-to-date, quarter-to-date, and trailing months.

Uploaded by

Harry Konnect
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

TRUNC (timestamp, [parts of timestamp])

Where [parts of timestamp] can be

'D'-- Return only day information in the timestamp. Hours, minutes, and seconds are
returned as zero.

'h'-- Return only day and hour information in the timestamp. Minutes and seconds are
returned as zero.

'm'-- Return only day, hour, and minute information in the timestamp. Seconds are
returned as zero.

's'-- Return only day, hour, and second information in the timestamp, but do not show
milliseconds.

TRUNC also can be used with decimal numbers to return a number rounded to a given number
of decimal places.

For example:

TRUNC(1234.567) returns 1,234

TRUNC(1234.567, 1) returns 12,345.6

TRUNC(1234.567, -2) returns 1,200

How to handle date related relational and dimensional functions


Date related relational functions

Make timestamp from date key


Parameters map is a good solution to get current date; however, it present challenges to directly use date
type, instead, data key as integer is easily to handle. In some cases, it is requested to turn it into real date in
report. Code below can help

_make_timestamp (
cast(#$CurrentDateKey{'Fact TableX'}# /10000 ,integer),
cast(#$CurrentDateKey{'Fact TableX'}# /100, integer) - ( cast(#$CurrentDateKey{'Fact TableX'}# /10000,
integer))*100,
#$CurrentDateKey{'Fact TableX'}# - cast((#$CurrentDateKey{'Fact TableX'}# /100),integer)*100 )

Get last complete month date


Date + 1 Day - 1 Month, then get last day of month.
_last_of_month (_add_months (_add_days ([Fact].[Dim Time].[Current Date],1),-1))

Make week start day


For report with weeks, it is requested to display the first day of each week. The data item can get first day of
each week.

case month(minimum([Dim Time].[Date] for [Dim Time].[Week Id]))


WHEN 1 THEN 'Jan'
WHEN 2 THEN 'Feb'
WHEN 3 THEN 'Mar'
WHEN 4 THEN 'Apr'
WHEN 5 THEN 'May'
WHEN 6 THEN 'Jun'
WHEN 7 THEN 'Jul'
WHEN 8 THEN 'Aug'
WHEN 9 THEN 'Sep'
WHEN 10 THEN 'Oct'
WHEN 11 THEN 'Nov'
WHEN 12 THEN 'Dec'
END
+
' ' + right('0' + cast(day(minimum([Dim Time].[Date] for [Dim Time].[Week Id])), varchar(2)), 2)

Half to date current year, prior year

When it is requested to get Half to date, get reference date first as data item, then get date started. CYTD-
Current year to date; PYTD- Prior year to date; CHTD-Current half year to date; PHTD-Prior half year to date

[Dim Time].[Date] between [DateFrom] and [DateTo]

[DateFrom]

case when ([Current Month Number] >6 ) and (?TimePeriodGrp?='CHTD' or ?TimePeriodGrp?='PHTD') then
_make_timestamp (year([DateTo]),07,01)

else _make_timestamp (year([DateTo]),01,01)

End

[DateTo]

case

when (?TimePeriodGrp?='CYTD') then ([Dim Time (Activity)].[ Current Date])

when (?TimePeriodGrp?='PYTD') then ( _add_years ([Dim Time (Activity)].[ Current Date], -1))
End

{ it also can be done by directly using filter


( ([Fact].[Dim Time].[Current Month Number] <7) and ([Fact].[Dim Time].[Year] = [Fact].[Dim Time].[Current
Year] ) ) OR ( ([Fact].[Dim Time].[Current Month Number] >=7) and ([Fact].[Dim Time].[Year] = [Fact].[Dim
Time].[Current Year] ) and [Fact].[Dim Time].[Month Number] >=7)
}

7d, MTD, YTD, PYTD

case when ?Relative Date?='7d'


then ( [Date] between _add_days(2007-05-17,-7) and (2007-05-17))
when ?Relative Date? ='MTD'
then( [Date] between _first_of_month(2007-05-17) and (2007-05-17))
when ?Relative Date? ='YTD'
then( [Date] between _add_days(2007-05-17,((_day_of_year(2007-05-17)-1)*-1))
and (2007-05-17))

Current YTD Sales:


if ( SalesDate between _make_timestamp(extract(year,current_date), 1, 1) and current_date )
then (SalesAmount)
else (0)

Prior YTD Sales:


if ( SalesDate between _make_timestamp((extract(year,current_date)-1), 1, 1) and _add_years(current_date,-
1) )
then (SalesAmount)
else (0)

Get Last month of data available

assume available date is [AvailableDate] and time dimension is [DimTime]: (year(_add_months (_add_days
([Namespace].[DimTime].[ AvailableDate],1),-1)) * 100) + month(_add_months (_add_days ([Namespace].[
DimTime].[ AvailableDate],1),-1))

Get start date and end date based on last available month

Get year start date

1)-_day_of_year ([End Date])


-366

2)_add_days ([End Date], -_day_of_year ([End Date])+1)


1-Jan-12 12:00:00 AM
Get last complete Month date

1)[Fact].[Dim Time].Current Date]


6-Jan-13 12:00:00 AM

2)_add_days ([Fact].[Dim Time].Current Date],1)


7-Jan-13 12:00:00 AM

3)_add_months (_add_days ([Fact].[Dim Time].Current Date],1),-1)


7-Dec-12 12:00:00 AM

4)_last_of_month (_add_months (_add_days ([Fact].[Dim Time].Current Date],1),-1))


31-Dec-12 12:00:00 AM

Get last 13 Months

[Fact Table].[Dim Time].[Month Id] >=


(year(_add_months (_add_days ([Fact Table].[Dim Time].[Current Date],1),-13)) * 100) +
month(_add_months (_add_days ([Fact Table].[Dim Time].[Current Date],1),-13))and
[Fact Table].[Dim Time].[Month Id] <=
(year(_add_months (_add_days ([Fact Table].[Dim Time].[Current Date],1),-1)) * 100) +
month(_add_months (_add_days ([Fact Table].[Dim Time].[Current Date],1),-1))

Show date in crosstab

cast(cast (extract (year,[Returned items (query)].[Time dimension].[Date]), Char


(4))+substring (cast(cast(_round (((extract (month,[Returned items (query)].[Time
dimension].[Date])/100)+1)*100,0),integer),Char(3)),2,2)+substring (cast(cast
(_round (((extract (day,[Returned items (query)].[Time dimension].[Date])/100)+1)
*100,0),integer),Char(3)),2,2),integer)

string2date (
substring (number2string ([Query1].[Date]),1,4)
+'-'+
substring (number2string ([Query1].[Date]),5,2)
+'-'+
substring (number2string ([Query1].[Date]),7,2)
)

For IBM DB2 the calculation should look like this:

cast_integer(cast_char (Year([Returned items (query)].[Time dimension].[Date]) ,4)

||
right( replace ('0'||cast_char (Month([Returned items (query)].[Time dimension].
[Date]) ,2),' ',''),2)
||
right(replace ('0'||cast_char (day([Returned items (query)].[Time dimension].[Date]) ,
2),' ',''),2))

For Microsoft SQLServer the calculation should look like this:

cast_integer(convert({varchar},[Returned items (query)].[Time dimension].[Date],112))

For Oracle:

to_number(To_Char([Returned items (query)].[Time dimension].[Date], 'YYYYMMDD'))

Useful links

Cognos Time and Date Functions from temple university

Find Current Period using closingPeriod Function


closingPeriod ([sales_and_marketing_cs].[Time].[Time].[Month])

Find Current Period by Filtering on Measure Data


item(tail(filter(members([sales_and_marketing].[Time].[Time].[Month]), tuple([Revenue],
currentMember([sales_and_marketing].[Time].[Time])) is not null), 1), 0)

Check link for detail explanation


http://www.ibm.com/developerworks/data/library/cognos/reporting/dimensional_queries/page561.html

Current Month/Quarter/YTD/ Trailing Twelve Months


Often use a “base” month current period to build everything else off of:
[Month Current] = closingPeriod( [goc].[Years].[Years].[Month] )

Quarter
parent( [Month Current] )

YTD
total( currentMeasure within set
periodsToDate( [goc].[Years].[Years].[Year], [Month Current] ) )

Trailing Twelve Months


total( currentMeasure within set
lastPeriods( 12, [Month Current] ) )

Month % Change Prior Year


( [Month Current] - [Month Prior Year] ) / [Month Prior Year]
Where [Month Prior Year] = lag( [Month Current] , 12 )

Note: currentMeasure is in the context of the crosstab


Period to date
[monthClosingPeriod] =
closingPeriod( [GOC].[Years].[Years].[Month] )

[periodsToDateForClosingPeriodMonth] =
PeriodsToDate( [GOC].[Years].[Years].[Year] , [monthClosingPeriod] )

Show real date from power cube

Current Day_Date
descendants ([Current Day],1)

Yesterday_Date
descendants ([Yesterday],1)

Useful links

Using the periodsToDate function within IBM Cognos 10 Report Studio to Calculate an OLAP
Running-Total

IBM Cognos 8 Framework Manager - Dimensional Modeling for Time Period Analysis

Oracle date functions


Get the last day of the week select trunc(sysdate, 'DAY')+6 from dual;

Get first day of year SELECT TRUNC(TO_DATE('17-DEC-2001'),'YEAR') "First Day" FROM Dual; Get
last Day of Current Month
SELECT add_months(trunc(sysdate) - (to_number(to_char(sysdate,'DD')) - 1), 1) -1 FROM dual

SQL server date functions

Get the first day of month DATEADD(dd,-(DAY(DT.DAY_DT)-1),DT.DAY_DT) Get date key select
cast(convert(varchar(8), getdate(), 112) as integer) Get last Sunday
Select cast(convert(varchar(8), dateadd(day,-datepart(weekday,dateadd(WEEK,-
1,GETDATE()))+1,dateadd(WEEK,-1,GETDATE())), 112) as integer)

Useful Query items

1. Get total reminding to go for product Category XYZ, set 0 if the reminding to go as 0

if (([Product Category] = 'XYZ') and (total ([Forecast] for [Province Id], [Product Category] ) -
total([Sales] for [Province Id], [Product Category]) > 0)) then ( total ([Forecast] for [Province Id],
[Product Category] ) - total([Sales] for [Province Id], [Product Category] )) else (0)

2. TYD, QTD and HTD based day ( Assume [Fact Current Date],[Fact Current Quarter Number] and
[Fact Current Quarter Number] )
#/* YTD at the begining of year*/#
_add_days ([End Date], -_day_of_year ([Fact Table].[Dim Time].[Fact Current Date])+1)

#/* QTD */#


if ([Fact Table].[Dim Time].[Quarter Id] = [Fact Table].[Dim Time].[Fact Current Year]*10+[Fact
Table].[Dim Time].[Fact Current Quarter Number])
then ([Fact Table].[Fact Table].[Measure])
else (0)

#/* HTD */#


If ( [Fact Table].[Dim Time].[Fact Current Quarter Number] > 2 ) Then
( If ( [Fact Table].[Dim Time].[Quarter Number] > 2) Then
( If ([Fact Table].[Dim Time].[Quarter Id] <= [Fact Table].[Dim Time].[Fact Current Year]*10+[Fact
Table].[Dim Time].[Fact Current Quarter Number])
Then [Fact Table].[Fact Table].[Measure])
else (0) )
Else ( 0) )
Else (
If ([Fact Table].[Dim Time].[Quarter Id]<=[Fact Table].[Dim Time].[Fact Current Year]*10+[Fact
Table].[Dim Time].[Fact Current Quarter Number])
then ([Fact Table].[Fact Table].[Measure])
else (0) )
Time filter
filter(
[Time Dimension].[Time Hierarchy].[Date],
roleValue('_businessKey', currentMember([Time Dimension].[Time Hierarchy])) >=
#sq(prompt('From', 'Date'))# and
roleValue('_businessKey', currentMember([Time Dimension].[Time Hierarchy])) <=
#sq(prompt('To', 'Date'))#
)

Identifying nth Weekday of a month in reports


Requirement: Identify the 2nd Thursday of the current month. Solution: Create data items ToDate,
1stDateofMonth, 1stDayofMonth, Nth, Day , AddDays, NthDay ToDate - current_date 1stDateofMonth -
_first_of_month(ToDate) 1stDayofMonth - _day_of_week(1stDateofMonth ,1) // Assuming Monday is Day 1
Nth - 2 // The nth value of the weekday required, in our case we require 2nd Thursday Day - 4 // Assuming
Monday is Day 1, then Thursday is Day 4 AddDays - case when [Day] >= [1stDayofMonth] then [Day] -
[1stDayofMonth] else ([Day] + [1stDayofMonth]) -1 end NthDay - _add_days([1stDateofMonth],(([Nth]-1) * 7
) + [AddDay]) NthDay returns the 2nd Thursday of the month.

Age calculation
We have two ways to calculate age in years and age in yy years mm months and dd days format

Calculate Age in years...

Create a query Calculation as below...

_years_between (current_date, [Birth date column])

Calculate Age in yy years, mm months and dd days format...

(replace [Birth Date] with your own Data of birth column)

substring (cast(_ymdint_between (current_date, [Birth date]),char(6)),1,2) || ' Years '||

substring (cast(_ymdint_between (current_date, [Birth date]),char(6)),3,2)

|| ' months ' ||

substring (cast(_ymdint_between (current_date, [Birth date]),char(6)),5,2)


|| ' Days '

http://cognosskills.blogspot.in/

=============

Cast date to string, want MM/DD/YYYY formatting (Read 3728


times)

Re: Cast date to string, want MM/DD/YYYY formatting

Have a column where the DOB was cast to a varchar. Want to hide certain birthdays so
XX/XX/XXXX shows under certain circumstances. When the cast to varchar was done it formatted
the date as 1994-02-03. I want the date formatted as MM/DD/YYYY. Is there a FORMAT
statement or such that can be done on the dates, or do I perform substrings to move the date
around?

I'd make the same suggestion I did for your other thread and use a conditional style rather than
changing the actual data type of the query item.

Yes, Lynn's suggestion on my other related thread worked like a charm. It was "how to format a
string as currency"

You can't substring a date.

Try these:
select cast(month(getdate()) as varchar(2)) + '/' + cast(day(getdate()) as varchar(2)) + '/' +
cast(year(getdate()) as varchar(4)) -- m/d/yyyy
select right('00' + cast(month(getdate()) as varchar(2)), 2) + '/' + right('00' +
cast(day(getdate()) as varchar(2)), 2) + '/' + right('0000' + cast(year(getdate()) as varchar(4)),
4) -- mm/dd/yyyy
select convert(varchar(10), getdate(), 101) -- mm/dd/yyyy

Replace the getdate() function with whatever your date expression is.

You might also like