You are on page 1of 32

http://stackoverflow.

com/questions/31710492/convert-a-column-that-has-a-data-
type-of-integer-into-date-in-cognos-report-stud

Convert a column that has a data type of integer into date in Cognos report studio

I have a column that appear like this and the data type is integer. I get that data from AS400
server that's why it uses integer data type. The date format is represent as YYYYMMDD

In report studio, I created a data item that would convert this integer column to date time. But
it failed.

I have tried lots of different approach but none of these worked.


cast([WCPDOD], 'YYYYMMDD')

cast([WCPDOD], date) UDA-SQL-0219 The function "to_date" is being used for local processing
but is not available as a built-in function, or at least one of its parameters is not supported.RSV-
SRV-0042

cast([WCPDOD], YYYY-MM-DD)

cast([WCPDOD], datetime)

cast_timestamp([WCPDOD], datetime)

cast_timestamp([WCPDOD], date)

cast_integer([WCPDOD], date)

Can someone help me with this? My goal is to get this 20150729 into this 07/29/2015 at least

First, cast your 10-digit integer into a string:

Data Item2
cast([Data Item1],varchar(10))
Next, use substring to extract out the date components and build a date string:

Data Item3
substring([Data Item2],1,4) + '-' + substring([Data Item2],5,2) + '-' + substring([Data Item2

Lastly, convert the resulting string to date format:

Data Item4
cast([Data Item3],date)
Of course, this can all be done in a single expression but I broke it out here for clarity.

In SQL Server, you can convert the integer field to varchar and then to a date and then use the
date style 101 to achieve your desired format:
DECLARE @datevalue int = '20150729';

SELECT convert(varchar(10),cast(cast(@datevalue AS varchar(10)) as date), 101);

It does not work when I apply this in Cognos report studio. Parsing error before or near position: 71 of:
"convert(varchar(10),cast(cast([WCPDOD] AS varchar(10)) as date), 101);

You will need to do this in your data layer (SQL Server I assume) where you are pulling the data in cognos

=============
OK, report studio is wried . . .

if I changed the code to this, it worked . . .

cast (year([Accident Date]),CHAR(4))

Now I am ready to construct the year and month string as follows:

cast (year([Payment Date]),CHAR(4)) + '-' + cast (month([Payment Date]),CHAR(2))

Output shows:

Payment Date Data Item1 Data Item2

Jan 1, 0001 1 1 -1

Jan 1, 1900 1900 1900-1

Jan 2, 1900 1900 1900-1

Jan 3, 1900 1900 1900-1

Question,

If the month is from Jan to Sept, how do I put a zero in the front

For example, Jan 1, 1990 will become 1990-01 (currently showing 1990-1 as above) ?

Thanks.

You have to modulate your month something like

cast(( ((month([Payment Date])/100)+1)*100),CHAR(2))

it returns for month 101 for januari (1/100=0,01 +1=1,01*100=101)

for december it is 112 (12/100=0,12+1=1,12*100=112)


THEN you use substring(month,2,2)= 01 for januari,,,,,12 for december

(I use duth version, thats why it is ; instead of , in syntax)

greatings

very simple, I would like to see a string YYYY-MM based on a [Payment Date] field.

This is the current situation:

If [Payment Date] has a value of 2010-10-1 and 2010-9-30, I would like to get

2010-10 and 2010-09

If I try to use the most proven working functions as below:

cast(extract(year,[Payment Date]),VARCHAR(4))

This would give the year '2010'

If use

cast(extract(month,[Payment Date]),VARCHAR(2))

This would give the month '10' and '9'

If use

repeat('0',2)

This would give '00'


If use

char_length (cast(extract(month,[Payment Date]),VARCHAR(2)))

This would give 2 and 1

If use

cast(extract(year,[Payment Date]),VARCHAR(4)) + '-' + repeat('0',2)

This would give

2010-00

The logic goes if I use Repeat to report the '0' as the leading zero for Sept, then the code should be

cast(extract(year,[Payment Date]),VARCHAR(4)) + '-' + repeat('0',(2-char_length


(cast(extract(month,[Payment

Date]),VARCHAR(2)))))

But this gave me an error of

An error occurred while performing operation 'sqlPrepareWithOptions' status='-126'.

I am really puzzled . . .

cast(extract(year,[date]),varchar(4))||'-'||

case when extract(month,[date]) < 10 then

'0'||cast(extract(month,[date]),varchar(1)) else

cast(extract(month,[date]),varchar(2)) end
)

=========

http://ravimahazan.blogspot.in/2014/11/use-of-cast-function-in-cognos-report.html

In general cast function defines as who transforms one data type of a column to other one as defined in
the function.

Syntax : cast (Column name ,desired_datatype(needs to define))

In report studio cast function is used to make two query item with different data type compatible with
each other.

There are different scenarios when cast function is used like to convert date column or to create dummy
column in UNION.

While using cast report author needs to keep in mind about the performance of report.

As any casting of query item is part of Cognos SQL rather than Native SQL,which processed at cognos
server end not at database.

In case you have any question please comment ,i will respond to your query.

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

Hi all

I have a my date as ' yyyymm' in the model query item(database ). e.g entrydate.

My filter is like this.


[entrydate] >= ?P_ENTRYDATE?

Obviously it does not work QE-DEF-0387 Invalid format for numeric prompt 'P_ENTRYDATE'.Could you please
advise on how to cast/convert the Date Prompt value from Date to 201010 format and where to use it.

Please help.
Thanks,
Nandini

Hi try this
parameter1 is parameter of Date prompt

Create a query calculation new_Date as


cast(extract(year,?Parameter1?),char(4))+cast(extract(month,?Parameter1?),char(2))

then disabled the filter on your date and add this


Your Date column=New_date

only check with the values for the month like its 201105 or 20115 my solution wil work
for 20115.
if its 201105 then u have make some extra efforts as

create Year ->cast(extract(year,?Parameter1?),char(4))

create Month as->


If(extract(month,?Parameter1?) >10) then
(cast(extract(month,?Parameter1?),char(4)))
else
('0'+cast(extract(month,?Parameter1?),char(4)))

then create New_Date as [Year]+[Date]

then apply the same filter


Your Date column=New_date

hi prince as per your solution (then disabled the filter on your date) which filter to disable. i dont have any filter for
date.

No just mean to say if u currently have added any filter on ur date column for filtering then disable it.else u can
skip this step.
Try and let me Know
Hi prince

I have a 'AND/OR' propmt in between the 2 date propmts which have the case statement as shown below.

case when (?Parameter AND-OR?)='AND'

then ((1 in_range ?P_ENTRDATE? OR [entrydate ]in_range ?P_ENTRDATE?) AND

(1 in_range ?P_TRANSACTION_DATE? OR
[entrydate] in_range ?P_TRANSACTION_DATE?))

else
((1 in_range ?P_ENTRYDATE? OR [entrydate] in_range ?P_BOOKING_ENTRY_MONTH?) OR

(1 in_range ?P_TRANSACTION_DATE? OR
[entrydate] in_range ?P_TRANSACTION_DATE?))

end

when i disable this filter iam not getting errors but mismatch of data. but when i enable it iam getting multilpe
errors.
dont knw wat exactly is the problem. pl guide me

Hi,
Try to cast the new_date column which we derived from date prompt to integer As Cast([Year]+[Date], Integer).
then keep
old filter as [entrydate] >= New_date

then enable Ur 'AND/OR' filter.

Thanks .

Hi prince
i have 2 date prompts, 1 is 'entry date prompt' and other is 'trans date prompt'. my report data depends on And/Or
selection prompt between these two date prompts.

little modification in the below case statement pl have a look and guide me further. there are 2 different data items
on which 2 different respective prompts depends(P_ENTRDATE >> entrydate, ?P_TRANSACTION_DATE? >>
transdate).

case when (?Parameter AND-OR?)='AND'

then ((1 in_range ?P_ENTRDATE? OR [entrydate ]in_range ?P_ENTRDATE?) AND


(1 in_range ?P_TRANSACTION_DATE? OR
[transdate] in_range ?P_TRANSACTION_DATE?))

else
((1 in_range ?P_ENTRYDATE? OR [entrydate] in_range ?P_BOOKING_ENTRY_MONTH?) OR

(1 in_range ?P_TRANSACTION_DATE? OR
[transdate] in_range ?P_TRANSACTION_DATE?))

end

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

I have a dropdown value prompt on prompt page which is populated using 'Calendar Date' field from 'Date'
Dimension.

Use values of value prompt is

_last_of_month ([Date].[Calendar Date])

cast (extract(day, [Calendar Date]),varchar(2)) + '-' +


case
when (extract(month, [Calendar Date])=1)
then 'JAN'
when (extract(month, [Calendar Date])=2)
then 'FEB'
when (extract(month, [Calendar Date])=3)
then 'MAR'
when (extract(month, [Calendar Date])=4)
then 'APR'
when (extract(month, [Calendar Date])=5)
then 'MAY'
when (extract(month, [Calendar Date])=6)
then 'JUN'
when (extract(month, [Calendar Date])=7)
then 'JUL'
when (extract(month, [Calendar Date])=8)
then 'AUG'
when (extract(month, [Calendar Date])=9)
then 'SEP'
when (extract(month, [Calendar Date])=10)
then 'OCT'
when (extract(month, [Calendar Date])=11)
then 'NOV'
when (extract(month, [Calendar Date])=12)
then 'DEC'
end + '-' +
cast (extract(year, [Calendar Date]),varchar(4))

or showing date in 'DD-MMM-YYYY' format.

I have also applied filter in query of value prompt query to display dates greater than '31-12-2008' which works
fine.

Till this point everything is functioning as expected but now Users want to see Current Month's last date should be
displayed when they run the report .

Could anyone please suggest how should I achieve this functionality?

You can sort the values in value prompt in desc order and apply one more filter in value prompt query like
calendar_Date<=current_Month.
Now you can add javascript to remove 1 st 2 line and making the 1stvalue as default value..

=======

Hi all

I have a problem where i am getting an error when filtering on a data item. Below is my data item,
so i want ot show in my list report an entered date for adjustments that are greater than 0 basically
else 2000-01-01.

My filter is below this case statement where i want to only show this the below case statement
which is lesser or greater than '2000-01-01'

I have also included my error and i have tried casting using many different casting functions.
My case statement called KMS Maintenance Date

CASE WHEN ([E-code]= 'C072') THEN ([ENTERED DATE])

WHEN ([Item Code]not


in('ABS','HBS','HDS','MH','ML','NWS','ORM','RAR20','SLB','SSH','TLC','WRS','CJ','EW','SLC','HJ','BL','M
RB','SLC','CTL','HSW','MRB','SLC')and[Item Code]not starts with 'F' and [Item Code]not
in('FLT','VAN','CAR','AR','TRAIL') and [Adjustment 1] <> 0 and [DATE] <=current_date) THEN
([ENTERED DATE])

WHEN ([Item Code]not


in('ABS','HBS','HDS','MH','ML','NWS','ORM','RAR20','SLB','SSH','TLC','WRS','CJ','EW','SLC','HJ','BL','M
RB','SLC','CTL','HSW','MRB','SLC')and[Item Code]not starts with 'F' and [Item Code]not
in('FLT','VAN','CAR','AR','TRAIL') and [Adjustment 5] <> 0) THEN ([ENTERED DATE]) ELSE ('2000-
01-01') END

My Filter

[KMS Maintenance Date]<> '2000-01-01'

My Error

UDA-SQL-0460 A general exception has occurred during local processing.

UDA-EE-0094 The operation "less_equal" is invalid for the following combination of data types:
"varchar" and "date2"

Thanks in Advance

Sounds like the "[DATE]" in your "and [DATE] <=current_date" part of the case statement needs to
be cast-ed to a date so that its data type matches what's being returned by "current_date".... or vice
versa I s'pose.
==================

Date Manipulation

I'm new to cognos and cant figure out how to do something that should be quite simple. I want to get the first day
of the month from a date from my stored procedure. I have tried cognos syntax, sql syntax, setting the connection
to Limited Local, setting the connection interface to OR instead of OL (saw this on a post and have no idea what it
would even do), and anything else i could find in the past few days. I just want to get the month from the procedure
data for grouping, graphing etc. Below i have some functions i have tried but all come back with the same
error. The function "insertfunctionnamehere" is being used for local processing but is not available as a
built-in function, or at least one of its parameters is not supported

I have tried....
month([fieldname])

_first_of_month([fieldname])

cast(convert(char(10),convert(char(2), datepart('MM',[fieldname]))+ '/01/' +convert(char(4),


datepart('YYYY',[fieldname])), 101) as datetime)

string2date(convert(char(10),convert(char(2), datepart('MM',[fieldname]))+ '/01/' +convert(char(4),


datepart('YYYY',[fieldname])), 101))

Please help!!! I have googled and searched forums and am completely out of ideas. Thanks.

You want to extract the month? I would just brute force it in Cognos by substring the datetime for the month
numbers, then parse that through a case statement to output January, February, March, etc.

I tried a substring to see if that would make any difference. It did make it a step farther as it tried to run the report
and got to and past the parameters but it failed with An error occurred while performing operation
'sqlOpenResult' status='-28'

So now i dont understand why i am getting this message. And i dont understand what was wrong with all my
previous attempts. Please Help!

btw, the command i tried this time was...


substring(cast([fieldname] as char), 1, 2)

Hi Thermos,

Just Try below one may give you solution.


To_Char([Field_Name],'mm/yyyy')
Then concatenate this with 01 at the starting or as per your date format.
Good Luck...
Sanjeev

Thanks for the reply, but i get the same Local Processing error. The syntax check is fine but
it fails when i try to run it.

to_char is being used for local processing but is not available as a built-in function, or
at least one of its parameters is not supported

I dont believe this is a syntax issue, there must be a setting wrong somewhere. Any other
ideas?

ok, I set the query properties: Processing = Limited Local and Rollup Processing = Local

and with this set one thing works. _first_of_month ([fieldname])


but everything else i try fails, such as: datepart, cast, to_char, substring, etc. so it appears that i can use any of the
"Business Date/Time Functions" with the way i have things set, but if i need to do anything else I'm out of luck.

what should i set things as to be able to use the other available functions in cognos?

you should be able to play with the values of those 2 and get your desired results. Not sure what is going on in your
case. Perhaps, start off with just your date item in your query and work to get the 1st day of month. Once you have
succeeded then proceed to add other items.

I am looking at your orginal post and you mention that you have a stored proc, from which you are trying to extract
the 1st day of month. Have you considered modifying either your SP or FM (Framework Manager) to calculate
what you want and then use it Report Studio?

I think i have enough working that i can fix this one problem, but i Really need to know why i can't do a dateadd,
datepart, etc. I get local processing is not available as a built-in function every time for those.

Kulkarni, thanks for you help and i realize i can do some of this in the procedure but i need a cognos fix. i can't go
back and add fields to SP's every time i need some cosmetic work for a report date header or something like that.

===========
Wednesday, 1 November 2017
Report Studio :Cognos Time and Date Functions

Cognos date and time functions

Date and Time Functions

cast(extract(year,current_ timestamp),varchar(4)) >>> 2014

extract(hour,current_timestamp) >>> 10

extract(day,current_timestamp) >>> 13

cast(extract(month,current_ timestamp),varchar(2)) >>> 7

cast(current_timestamp,varchar(50)) >>> 2012-07-13 10:44:32.991000000+04:70

cast(extract(hour,current_ timestamp),varchar(2)) >>> 10

Last Day of Current Month _last_of_month (current_timestamp)

Date Minus 24 Hours _add_days ((current_timestamp),-1)

Extract minute as two digit alpha: case (CAST(extract ( minute, current_timestamp), VARCHAR(2)))

when '0' then ('00')

when '1' then ('01')

when '2' then ('02')

when '3' then ('03')

when '4' then ('04')

when '5' then ('05')

when '6' then ('06')

when '7' then ('07')

when '8' then ('08')

when '9' then ('09')

else (CAST(extract ( minute, current_timestamp), VARCHAR(2)))

end

get prior month based on current month


extract(month,_add_months( current_timestamp,-1))
This CASE function extracts the first two characters of the current date CASE (substring(cast(current_ timestamp,varchar(50)),6,2))
and translates it
WHEN '07' THEN '04'
into a financial period:
WHEN '08' THEN '05'

WHEN '09' THEN '06'

WHEN '10' THEN '07'

WHEN '11' THEN '08'

WHEN '12' THEN '09'

WHEN '01' THEN '10'

WHEN '02' THEN '11'

WHEN '03' THEN '12'

WHEN '04' THEN '01'

WHEN '05' THEN '02'

WHEN '06' THEN '03'

ELSE '14'

END

Calculate the financial year based on the current date Apr-Mar

if (extract(month,current_timestamp)♥)

then

timestamp)-1,varchar(4))+'-'+

timestamp),varchar(4))

else

timestamp),varchar(4))+'-'+

timestamp)+1,varchar(4))

)
Dec-Nov

if (extract(month,current_timestamp)<11)

then

timestamp)-1,varchar(4))+'-'+

timestamp),varchar(4))

else

timestamp),varchar(4))+'-'+

timestamp)+1,varchar(4))

First day of this year _add_days(Current_date ; (_day_of_year(Current_date)*-1)+1 )

_first_of_month(_add_years(current_date;-1))

First day of last year (only used in january): OR

_last_of_month(_add_months (current_date;-1))

date-to-string substring(cast(extract(month,[Project Start Date]),VARCHAR(10)),1,2)


+ '/' + substring(cast(extract(year,[Project Start
Date]),VARCHAR(10)),3,2) + ' - ' +
substring(cast(extract(month,[Project End Date]),VARCHAR(10)),1,2) +
'/' + substring(cast(extract(year,[Project End
Date]),VARCHAR(10)),3,2)

OR

substring(cast(extract(month,[Project Start Date]),VARCHAR(10)),1,2)


+ '/' + substring(cast(extract(year,[Project Start
Date]),VARCHAR(10)),3,2) + ' - ' +
substring(cast(extract(month,[Project End Date]),VARCHAR(10)),1,2) +
'/' + substring(cast(extract(year,[Project End
Date]),VARCHAR(10)),3,2)

CAST and EXTRACT Functions:

Where [Time stamp] = Jun 8, 2009 5:26:47 PM


Expression Result

cast(extract( year, [Time stamp]), varchar(4)) 2009 (alpha)

extract( hour, [Time stamp]) 17 (numeric)

extract( day, [Time stamp]) 8 (numeric)

cast(extract(month,[Time stamp]),VARCHAR(2)) 6 (alpha – note lack of leading zero)

cast([Time stamp], date) Jun 8, 2009 (‘date’ is a data type)

cast ([Time stamp], varchar(50)) 2009-06-08 00:00:00.000000000

cast(extract (hour,[Time stamp]), VARCHAR(2)) 5 (alpha)

Extract minute as two digit alpha:

case (CAST(extract ( minute, [Audit].[Run Reports].[Time stamp]), VARCHAR(2)))

when '0' then ('00')

when '1' then ('01')

when '2' then ('02')

when '3' then ('03')

when '4' then ('04')

when '5' then ('05')

when '6' then ('06')

when '7' then ('07')

when '8' then ('08')

when '9' then ('09')

else (CAST(extract ( minute, [Audit].[Run Reports].[Time stamp]), VARCHAR(2)))

end

or

TO_CHAR([Time stamp], ‘MM’)

Last Day of Current Month:

_last_of_month(date2timestamp(Today()))

Date Minus 24 Hours:


_add_days([Audit].[COGIPF_RUNREPORT].[TIME STAMP],-1)

Use a date in a filter:

[Audit].[Run Reports].[Time stamp] > cast('2010-05-01', timestamp)

or

cast ([CURRENT_HIRE_DATE], varchar(50)) > '2005-11-10 00:00:00.000000000'

Note: Strangely, [Audit].[Run Reports].[Time stamp] = cast('2010-05-01', timestamp)

does not work as a filter. However, the following does work:

Between Function:

[Time stamp] between (cast('2010-05-10', timestamp)) and (cast('2010-05-11', timestamp))

To restrict a report based on a hard coded date (ex. 5/10/2010):

cast ([Time stamp], varchar(50)) = '2010-05-10 00:00:00.000000000'

To filter records based on dates in prior month (based on system date):

extract(month, _add_months(current_date, -1)) = cast(extract(month,[Time stamp]),varchar(2))

To filter records based on a timestamp when using date prompts on a prompt page:

Filter1: [TIME STAMP] >= cast((?beginDate?) as TIMESTAMP)

Filter2: [TIME STAMP] <= _add_days(cast((?endDate?) as TIMESTAMP),1)

(A day is added to the end date to allow for the use of a single day range. That is, the

beginDate will be Apr 27, 2012 12:00:00 AM if April 27 is selected. If April 27 is also

selected as the end date, 24 hours must be added so that the end date used in the filter

is Apr 28, 2012 12:00:00 AM)


SYSDATE:

This CASE function extracts the first three characters of the current date and translates it
into a fiscal period:

CASE (substr({sysdate},4,3))
WHEN 'JUL' THEN '01'

WHEN 'AUG' THEN '02'

WHEN 'SEP' THEN '03'

WHEN 'OCT' THEN '04'

WHEN 'NOV' THEN '05'

WHEN 'DEC' THEN '06'

WHEN 'JAN' THEN '07'

WHEN 'FEB' THEN '08'

WHEN 'MAR' THEN '09'

WHEN 'APR' THEN '10'

WHEN 'MAY' THEN '11'

WHEN 'JUN' THEN '12'

ELSE '14'

END

To calculate the fiscal year based on the current date (fiscal year for 2009/2010 is 2010):

IF (extract( month, {sysdate}) < 7)

THEN (cast(extract(year, {sysdate}), varchar(4)))

ELSE (cast(extract(year, {sysdate})+1, varchar(4)))

This function will return the date of the same day of the week a year ago and controls for

leap years. For example, if today is Tuesday, 07/31/2012 then the function returns

08/02/2012 (Tuesday) – trunc removes the time portion of the date value:
trunc(_add_days({sysdate},-364))

TO_CHAR:

General format is TO_CHAR(datetime, ‘format element’)

Example: TO_CHAR(current_date, ‘YYYYMM’) = 201012 (December, 2010)

Element Description
D Number of day of the week

DD Number of day of the month

DAY Name of the day (ex. FRIDAY)

HH Hour of day (1-12)

HH24 Hour of day (0-23)

MI Minute (0-59)

MM Month (January = 01…December = 12)

MONTH Name of month

MON Abbreviated name of month

SS Seconds

WW Week of year (1-53)

W Week of month (1-5 where week 1 starts on first day of month and ends

on seventh)

YYYY 4-digit year (YY returns last two digits of 4-digit year)

Year and Month in YYYYMM format:


Current year/month – to_char(current_date,'YYYYMM') ex: 200910

Previous month - to_char(add_months(current_date,-1),'YYYYMM') ex: 200909

Previous year/month- to_char(add_months(current_date,-13),'YYYYMM') ex: 200809

OTHER

Age in years:
_age([BENEFICIARY_BIRTH_DATE]) / 100
Age in years:
_years_between(current_date,[Date of Birth]) returns number of full years between the two dates

Age at time of graduation in years and fractional months:

_months_between ([OUTCOME_GRADUATION_DATE],[BIRTH_DATE])/12 returns

number of full years and fractional months (ex: 21.4) as of the date of graduation

Previous month:
extract(month, _add_months(current_date, -1))

Add/subtract months:

'20' || substrb(to_char(_add_months([Time stamp],-24)),8,2)

– This will subtract 24 months from the Time stamp month and display the resulting

year.

TRUNC (supplied by H. Cleveland)

TRUNC(date, [format])

Where [format] is optional and can be any of the following:

Year SYYYY, YYYY, YEAR, SYEAR, YYY, YY, Y

ISO Year IYYY, IY, I

Quarter Q

Month MONTH, MON, MM, RM

Week WW

IW IW

W W

Day DDD, DD, J

Start day of the week DAY, DY, D

Hour HH, HH12, HH24

Minute MI
Examples:

Functions Sytax

Start of today trunc({sysdate})

Start of yesterday (trunc(_add_days({sysdate}, -1),'dd'))

Start of Current Month trunc({sysdate},'mm')

End of Current Month last_day({sysdate})

Start of Previous Month trunc((trunc({sysdate},'mm')-1),'mm')

End of Previous Month trunc({sysdate},'mm')-1

Start of Current Quarter trunc({sysdate},'q')

End of Current Quarter add_months(trunc({sysdate},'q'),3)-1

Start of Previous Quarter trunc(trunc({sysdate},'q')-1,'q')

End of Previous Quarter trunc({sysdate},'q')-1

Start of Current Year trunc({sysdate},'y')

End of Current Year add_months(trunc({sysdate},'y'),12)-1

Start of Previous Year trunc(trunc({sysdate},'y')-1,'y')

End of Previous Year trunc({sysdate},'y')-1 When [TIME STAMP] = Aug 3, 2010 5:05:45 PM

Start of day in [TIME STAMP] trunc(_add_days([TIME STAMP], 0),'dd') = Aug 3, 2010 12:00:00 AM

Start of day previous to day in [TIME STAMP] trunc(_add_days([TIME STAMP],-1),'dd') = Aug 2, 2010 12:00:00 AM

Start of the hour in [TIME STAMP] trunc([TIME STAMP], 'hh') = Aug 3, 2010 5:00:00 PM

All records that occurred yesterday [TIME STAMP] between (trunc(_add_days({sysdate}, -1),'dd')) and
(trunc({sysdate}))

Day of week for current date _day_of_week(current_date , 1)

If it's Monday, include Decision Dates = Sat, Sun or Mon (((_day_of_week(current_date,1) = 1 ) AND
otherwise DECISION DATE = Current Date:
([Admission Application].[Admissions
Application].[LATEST_DECISION_DATE]

BETWEEN (current_date - 2) AND current_date))

OR

((_day_of_week(current_date,1) <> 1) AND

([Admission Application].[Admissions
Application].[LATEST_DECISION_DATE] =

current_date)))

If it’s Monday, then include any record beginning with the start of Friday
through the start

of Monday, otherwise include any record beginning with the start of


yesterday through

the start of Today: ((_day_of_week(current_date,1) = 1 ) AND

([Audit].[COGIPF_RUNREPORT].[TIME STAMP] BETWEEN

(trunc(_add_days({sysdate}, -3),'dd')) AND (trunc({sysdate})))

OR

((_day_of_week(current_date,1) <> 1) AND

([Audit].[COGIPF_RUNREPORT].[TIME STAMP] BETWEEN

(trunc(_add_days({sysdate}, -1),'dd')) AND (trunc({sysdate})))))

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