You are on page 1of 13

6/28/2016

CognosSkills
0

More NextBlog

CreateBlog SignIn

CognosSkills
Labels

Wednesday,1November2017

1.BestPracticeinReportStudio(4)

ReportStudio:CognosTimeandDateFunctions

2.REPORTSTUDIOTECHNICS(1)
AboutCognos(1)

Cognosdateandtimefunctions

BurstReportsandMasterDetail
Relationships(1)
BurstingCognosReporttoafile
system(1)
DateandTimeFunctions

CalendarStyleReportinReport
Studio(1)

cast(extract(year,current_timestamp),varchar(4))

>>>2014

extract(hour,current_timestamp)

>>>10

Charts(3)

extract(day,current_timestamp)

>>>13

CoalesceStatement(1)

cast(extract(month,current_timestamp),varchar(2))

>>>7

Cognos:JavaScriptSamples(3)

cast(current_timestamp,varchar(50))

>>>2012071310:44:32.991000000+04:70

cast(extract(hour,current_timestamp),varchar(2))

>>>10

Cognos:AddStaticChoicestoReport
Prompt(1)

LastDayofCurrentMonth

_last_of_month(current_timestamp)

Cognos10ActiveReports(1)

DateMinus24Hours

_add_days((current_timestamp),1)

Cognos10Cookbooks(1)

Extractminuteastwodigitalpha:

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

Cognos10InterviewQuestion(1)

when'0'then('00')

Cognos10newfeatures(1)

when'1'then('01')

Cognos8InterviewQuestion(1)

when'2'then('02')

Cognos8ReportStudioRotateText
(1)

when'3'then('03')

COGNOSBIFAQs(3)

when'4'then('04')

CognosDeploymentAcross
Environments(1)

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
getpriormonthbasedoncurrentmonth

extract(month,_add_months(current_timestamp,1))

ThisCASEfunctionextractsthefirsttwocharactersofthe

CASE(substring(cast(current_timestamp,varchar(50)),6,2))

currentdateandtranslatesit
intoafinancialperiod:

WHEN'07'THEN'04'
WHEN'08'THEN'05'
WHEN'09'THEN'06'

CognosIssues(1)
CognosRealtimeQuestionsAnd
Answers(1)
CognosReportStudioFaq's(1)
COGNOSReportStudioFAQs(1)
CognosReportStudioQuestions(1)
CognosReportStudioSome
terminologiesandLogics(1)
CognosSummariesFunctions(1)
Cognos:CreatingGanttChartusing
Crosstab(1)
COGNOS:HCLINTERVIEW
QUESTIONS(1)
Cognos:MasterDetailReport(1)

WHEN'11'THEN'08'

Cognos:PublishingPackagefroma
Cube(1)

WHEN'01'THEN'10'
WHEN'02'THEN'11'
WHEN'03'THEN'12'
WHEN'04'THEN'01'
WHEN'05'THEN'02'

http://cognosskills.blogspot.in/

CognosHotFile(1)

WHEN'10'THEN'07'

WHEN'12'THEN'09'

Calculatethefinancialyearbasedonthecurrentdate

CognosHistory(1)

Cognos:SavingReportstoaLocal
Directory(1)
commentcodeinCognosReport
Studio(1)
Congnos:FactlessFactTable?(1)
CreatingcheckboxinCognosReport
Studio(1)

WHEN'06'THEN'03'

DatawareHouseQuestions(1)

ELSE'14'

DatefunctionsinReportStudio(2)

END

DatePromptsbasedonRadioButton
Selection(1)

AprMar

daterelatedrelationaland

1/13

6/28/2016

CognosSkills
if(extract(month,current_timestamp))

dimensionalfunctions(1)

then

Differencebetweengroupbyclause
andorderbyclause(1)

DifferencebetweenODS&DWH(1)

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

DynamicSelectionofColumnsin
IBMReportStudio(1)

timestamp),varchar(4))

FAQ'S(9)

FullOuterJoints(1)

else

HierarchicDrilldown(1)

HowtocommentcodeinCognos
ReportStudio?(1)

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

Howtocreatealistreportthat
alternatestherowcolorsinCognos
ReportStudio(1)

timestamp)+1,varchar(4))
)
DecNov
if(extract(month,current_timestamp)<11)
then

HPInterviewQuestions(1)

IBMCognosBIInterviewQuestions
(1)

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

IBMCognosReportsPerformance
tuningScenarios(1)

timestamp),varchar(4))
)

IBMInterviewQuestions(1)

else

IntroductiontoCognos8BI(1)

JavaScriptSamples(4)
LimitationDescendantsMDX
FunctionagainstSets/Hierarchy(1)

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

LocalFileAccessLoadPrompt
ValuesfromaFile(1)

timestamp)+1,varchar(4))
)
Firstdayofthisyear

Howtoselectmultiplecolumnsfrom
avaluepromptinCognosList
report?(1)

_add_days(Current_date(_day_of_year(Current_date)*1)+1)

MissingFeaturesinCognos(1)

_first_of_month(_add_years(current_date1))

QuickTipstoImproveCognosBI(1)
ReportDesignBestPractices(1)

Firstdayoflastyear(onlyusedinjanuary):

ReportStudio:Cognos10Chart
Properties(1)

OR

_last_of_month(_add_months(current_date1))
datetostring

substring(cast(extract(month,[ProjectStart
Date]),VARCHAR(10)),1,2)+'/'+substring(cast(extract(year,
[ProjectStartDate]),VARCHAR(10)),3,2)+''+
substring(cast(extract(month,[ProjectEnd
Date]),VARCHAR(10)),1,2)+'/'+substring(cast(extract(year,

[ProjectEndDate]),VARCHAR(10)),3,2)

OR

substring(cast(extract(month,[ProjectStart
Date]),VARCHAR(10)),1,2)+'/'+substring(cast(extract(year,
[ProjectStartDate]),VARCHAR(10)),3,2)+''+
substring(cast(extract(month,[ProjectEnd
Date]),VARCHAR(10)),1,2)+'/'+substring(cast(extract(year,
[ProjectEndDate]),VARCHAR(10)),3,2)

Where[Timestamp]=Jun8,20095:26:47PM

Expression

Result

cast(extract(year,[Timestamp]),varchar(4))

2009(alpha)

extract(hour,[Timestamp])

17(numeric)

extract(day,[Timestamp])

8(numeric)

cast(extract(month,[Timestamp]),VARCHAR(2))

6(alphanotelackofleadingzero)

cast([Timestamp],date)

Jun8,2009(dateisadatatype)

cast([Timestamp],varchar(50))

2009060800:00:00.000000000

cast(extract(hour,[Timestamp]),VARCHAR(2))

5(alpha)

http://cognosskills.blogspot.in/

ReportStudio:Creatinga"Top10+
Others"dimensionalreport(1)
ReportStudio:CreatingaRowina
CrosstabthatCalculatesthe
DifferencebetweentheColumns(1)
ReportStudio:DefectDrillonMDX
expressionbasedmembers(1)
ReportStudio:Determinants
ExplainedwithExample(Hierarchic
Drilldown)(1)
ReportStudio:DynamicRowsPer
Page(1)
ReportStudio:DynamicSorting
ControlsfromIBMCognos(1)
ReportStudio:EffectiveDashboards
(1)
ReportStudio:Hide/DisplayDrill
ThroughLinksbasedonLevels(1)

CASTandEXTRACTFunctions:

Extractminuteastwodigitalpha:

ReportStudio:CognosDisasters:
Charts(1)

ReportStudio:ImpactofSumary
Filtersonreports(1)
ReportStudio:Implementing
DefaultDatePromptScenarioin
ReportPagesusingJavascriptand
RenderVariableConcept(1)
ReportStudio:Implementing
OptionalTables/FiltersInclusion
basedonPrompt(1)
ReportStudio:JavaScriptforDate
Validation(1)
ReportStudio:JavaScriptSamples
(6)
ReportStudio:JavaScriptto
DeselectValuePromptBox
Selections(1)

2/13

6/28/2016

CognosSkills
case(CAST(extract(minute,[Audit].[RunReports].[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,[Audit].[RunReports].[Timestamp]),VARCHAR(2)))
end

or

TO_CHAR([Timestamp],MM)

LastDayofCurrentMonth:

ReportStudio:LayoutCalculations
involving_add_days/_add_years
functions(1)
ReportStudio:MovingAggregate
CalculationsonDimensionalModel
(1)
ReportStudio:OptionalPrompt
Pages(1)
ReportStudio:Playingaroundwith
CMS(CognosMashupServices)(1)
ReportStudio:PracticalUsagefor
Sectioning(1)
ReportStudio:RefreshButton
CosmeticIssues(1)
Reportstudio:RemovingParameter
NamefromValuePrompts(1)
ReportStudio:SetFontforDate
PromptsusingJavaScript(1)
ReportStudio:ToporBottom
SellingProductsagainstDimensional
Model(1)

_last_of_month(date2timestamp(Today()))

ReportStudio:TreePrompton
RelationalModelsusingPromptAPI
(1)

DateMinus24Hours:

ReportStudio:TreePrompts
Explained(1)

_add_days([Audit].[COGIPF_RUNREPORT].[TIMESTAMP],1)

Useadateinafilter:

ReportStudio:XPath(1)
ReportStudio:CognosTimeand
DateFunctions(1)

[Audit].[RunReports].[Timestamp]>cast('20100501',timestamp)

ReportStudio:DefectAdvanced
DrillLinkwithHigherlevelDefault
promptselections?(1)

or

ReportStudio:SortingAsc/Descon
SameColumn(1)
ReportStudioIssues(1)

cast([CURRENT_HIRE_DATE],varchar(50))>'2005111000:00:00.000000000'

ReportStudioPerformance(1)
ReportStudioQuestions(1)

Note:Strangely,[Audit].[RunReports].[Timestamp]=cast('20100501',timestamp)
doesnotworkasafilter.However,thefollowingdoeswork:

ReportStudio:100%stackedBar
chartdisplayingpercentagesinbars
usingJavaScript(1)

BetweenFunction:

ReportStudio:Bursting(1)

[Timestamp]between(cast('20100510',timestamp))and(cast('20100511',timestamp))

Torestrictareportbasedonahardcodeddate(ex.5/10/2010):

cast([Timestamp],varchar(50))='2010051000:00:00.000000000'

ReportStudio:CreatingGanttChart
usingCrosstab(1)
ReportStudio:Insertinglistrowcells
inthelistheader(1)
ReportStudio:MasterDetailReport
(1)

Tofilterrecordsbasedondatesinpriormonth(basedonsystemdate):

ReportStudio:Mouseoverpopup
withourowntextboxusingjava
script(1)

extract(month,_add_months(current_date,1))=cast(extract(month,[Timestamp]),varchar(2))

ReportSudio:LayoutComponent
References(1)
ReportTips(1)

Tofilterrecordsbasedonatimestampwhenusingdatepromptsonapromptpage:

Filter1:[TIMESTAMP]>=cast((?beginDate?)asTIMESTAMP)

Filter2:[TIMESTAMP]<=_add_days(cast((?endDate?)asTIMESTAMP),1)

(Adayisaddedtotheenddatetoallowfortheuseofasingledayrange.Thatis,the
beginDatewillbeApr27,201212:00:00AMifApril27isselected.IfApril27isalso
selectedastheenddate,24hoursmustbeaddedsothattheenddateusedinthefilter
isApr28,201212:00:00AM)

SYSDATE:

ThisCASEfunctionextractsthefirstthreecharactersofthecurrentdateandtranslatesit
intoafiscalperiod:

http://cognosskills.blogspot.in/

SQLorMDXforanentireCognos
Reportstudioreport(1)
TemplatesvsLayoutComponent
References(1)
TheBurstQueryorReportQuery(1)
UsefulCognosDocumentationLinks
(1)
UsingStoredProceduresinReports
(1)
WhatisFactTable(1)
PopularPosts

(notitle)
REPORTSTUDIO
TECHNICSListof
TopicsinthisArtical:

3/13

6/28/2016

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

Performance
improvementIdeasforaReport.
BookmarksinCognosPAGEBREAK
IN...

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

Tocalculatethefiscalyearbasedonthecurrentdate(fiscalyearfor2009/2010is2010):

IF(extract(month,{sysdate})<7)
THEN(cast(extract(year,{sysdate}),varchar(4)))
ELSE(cast(extract(year,{sysdate})+1,varchar(4)))

Thisfunctionwillreturnthedateofthesamedayoftheweekayearagoandcontrolsfor
leapyears.Forexample,iftodayisTuesday,07/31/2012thenthefunctionreturns
08/02/2012(Tuesday)truncremovesthetimeportionofthedatevalue:

trunc(_add_days({sysdate},364))

TO_CHAR:
GeneralformatisTO_CHAR(datetime,formatelement)
Example:TO_CHAR(current_date,YYYYMM)=201012(December,2010)

(notitle)
ReportStudio:Tree
PromptsExplainedA
TreePromptprovides
theuserwithabilityto
navigatelevelsinahierarchyeasily
andsel...
(notitle)
ReportStudio:Cognos
TimeandDate
FunctionsCognosdate
andtimefunctionsDateandTime
Functionscast(extr...
(notitle)
ReportStudio:
JavaScriptSamples
Here'sacollectionofall
JavaScriptArticlesthat
canbefoundinthisblog:1.Removing
Param...
(notitle)
BurstingExplainedI
havebeenaskedbyso
manyuserswhat
happensbehindthe
sceneswhenCognosburstsareport?
Whydoburst...
(notitle)
ReportStudio:Mouse
overpopupwithour
owntextboxusingjava
scriptCognos:Mouse
overpopupwithourowntextbox
usingjava...

ElementDescription
DNumberofdayoftheweek
DDNumberofdayofthemonth
DAYNameoftheday(ex.FRIDAY)
HHHourofday(112)
HH24Hourofday(023)
MIMinute(059)
MMMonth(January=01December=12)
MONTHNameofmonth
MONAbbreviatednameofmonth
SSSeconds
WWWeekofyear(153)
WWeekofmonth(15whereweek1startsonfirstdayofmonthandends

(notitle)
DatePromptsbasedon
RadioButtonSelection
BusinessCase:Manya
times,youmaywantto
giveuserstheoptiontorunthe
reportfor...
(notitle)
CognoscompleteFAQ'S
1.DataWarehouse
Concepts
2.Introductionto
Cognos8BI3.DimensionalModeling
4.FrameworkManager5....

onseventh)
YYYY4digityear(YYreturnslasttwodigitsof4digityear)

YearandMonthinYYYYMMformat:
Currentyear/monthto_char(current_date,'YYYYMM')ex:200910

(notitle)
QuickTipstoImproveCognosBI
BurstingPerformance:Note:Thisis
innowayanexhaustiveguideto
improveburstperformance.I...

Previousmonthto_char(add_months(current_date,1),'YYYYMM')ex:200909
Previousyear/monthto_char(add_months(current_date,13),'YYYYMM')ex:200809

OTHER

Ageinyears:

(notitle)
ReportStudio:DynamicSorting
ControlsfromIBMCognosCognos
seemstohavecomeupwithnew
controls/methodfordynamic
column...

_age([BENEFICIARY_BIRTH_DATE])/100

Ageinyears:
_years_between(current_date,[DateofBirth])returnsnumberoffullyearsbetweenthetwodates

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

http://cognosskills.blogspot.in/

4/13

6/28/2016

CognosSkills
numberoffullyearsandfractionalmonths(ex:21.4)asofthedateofgraduation

Previousmonth:
extract(month,_add_months(current_date,1))

Add/subtractmonths:

'20'||substrb(to_char(_add_months([Timestamp],24)),8,2)

Thiswillsubtract24monthsfromtheTimestampmonthanddisplaytheresulting
year.

TRUNC(suppliedbyH.Cleveland)

TRUNC(date,[format])

Where[format]isoptionalandcanbeanyofthefollowing:

YearSYYYY,YYYY,YEAR,SYEAR,YYY,YY,Y
ISOYearIYYY,IY,I
QuarterQ
MonthMONTH,MON,MM,RM
WeekWW
IWIW
WW
DayDDD,DD,J
StartdayoftheweekDAY,DY,D
HourHH,HH12,HH24
MinuteMI

Examples:

Functions

Sytax

Startoftoday

trunc({sysdate})

Startofyesterday

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

StartofCurrentMonth

trunc({sysdate},'mm')

EndofCurrentMonth

last_day({sysdate})

StartofPreviousMonth

trunc((trunc({sysdate},'mm')1),'mm')

EndofPreviousMonth

trunc({sysdate},'mm')1

StartofCurrentQuarter

trunc({sysdate},'q')

EndofCurrentQuarter

add_months(trunc({sysdate},'q'),3)1

StartofPreviousQuarter

trunc(trunc({sysdate},'q')1,'q')

EndofPreviousQuarter

trunc({sysdate},'q')1

StartofCurrentYear

trunc({sysdate},'y')

EndofCurrentYear

add_months(trunc({sysdate},'y'),12)1

StartofPreviousYear

trunc(trunc({sysdate},'y')1,'y')

EndofPreviousYear

trunc({sysdate},'y')1When[TIMESTAMP]=Aug3,20105:05:45PM

Startofdayin[TIMESTAMP]

trunc(_add_days([TIMESTAMP],0),'dd')=Aug3,201012:00:00AM

Startofdayprevioustodayin[TIMESTAMP]

trunc(_add_days([TIMESTAMP],1),'dd')=Aug2,201012:00:00AM

Startofthehourin[TIMESTAMP]

trunc([TIMESTAMP],'hh')=Aug3,20105:00:00PM

Allrecordsthatoccurredyesterday

[TIMESTAMP]between(trunc(_add_days({sysdate},1),'dd'))and
(trunc({sysdate}))

Dayofweekforcurrentdate

_day_of_week(current_date,1)

Ifit'sMonday,includeDecisionDates=Sat,SunorMon

(((_day_of_week(current_date,1)=1)AND

otherwiseDECISIONDATE=CurrentDate:

([AdmissionApplication].[AdmissionsApplication].
[LATEST_DECISION_DATE]
BETWEEN(current_date2)ANDcurrent_date))

OR

((_day_of_week(current_date,1)<>1)AND
([AdmissionApplication].[AdmissionsApplication].
[LATEST_DECISION_DATE]=

http://cognosskills.blogspot.in/

5/13

6/28/2016

CognosSkills
current_date)))
IfitsMonday,thenincludeanyrecordbeginningwiththestartof
Fridaythroughthestart
ofMonday,otherwiseincludeanyrecordbeginningwiththestartof
yesterdaythrough
thestartofToday:

((_day_of_week(current_date,1)=1)AND
([Audit].[COGIPF_RUNREPORT].[TIMESTAMP]BETWEEN
(trunc(_add_days({sysdate},3),'dd'))AND(trunc({sysdate})))

OR

((_day_of_week(current_date,1)<>1)AND
([Audit].[COGIPF_RUNREPORT].[TIMESTAMP]BETWEEN
(trunc(_add_days({sysdate},1),'dd'))AND(trunc({sysdate})))))

TRUNC(timestamp,[partsoftimestamp])
Where[partsoftimestamp]canbe

'D'Returnonlydayinformationinthetimestamp.Hours,minutes,andsecondsare
returnedaszero.

'h'Returnonlydayandhourinformationinthetimestamp.Minutesandsecondsare
returnedaszero.

'm'Returnonlyday,hour,andminuteinformationinthetimestamp.Secondsare
returnedaszero.

's'Returnonlyday,hour,andsecondinformationinthetimestamp,butdonotshow
milliseconds.

TRUNCalsocanbeusedwithdecimalnumberstoreturnanumberroundedtoagivennumber
ofdecimalplaces.

Forexample:

TRUNC(1234.567)returns1,234

TRUNC(1234.567,1)returns12,345.6

TRUNC(1234.567,2)returns1,200

Howtohandledaterelatedrelationalanddimensionalfunctions

Daterelatedrelationalfunctions
Maketimestampfromdatekey
Parametersmapisagoodsolutiontogetcurrentdatehowever,itpresentchallengestodirectlyusedatetype,instead,
datakeyasintegeriseasilytohandle.Insomecases,itisrequestedtoturnitintorealdateinreport.Codebelowcanhelp

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

Getlastcompletemonthdate
Date+1Day1Month,thengetlastdayofmonth.

_last_of_month(_add_months(_add_days([Fact].[DimTime].[CurrentDate],1),1))

http://cognosskills.blogspot.in/

6/13

6/28/2016

CognosSkills

Makeweekstartday
Forreportwithweeks,itisrequestedtodisplaythefirstdayofeachweek.Thedataitemcangetfirstdayofeachweek.

casemonth(minimum([DimTime].[Date]for[DimTime].[WeekId]))
WHEN1THEN'Jan'
WHEN2THEN'Feb'
WHEN3THEN'Mar'
WHEN4THEN'Apr'
WHEN5THEN'May'
WHEN6THEN'Jun'
WHEN7THEN'Jul'
WHEN8THEN'Aug'
WHEN9THEN'Sep'
WHEN10THEN'Oct'
WHEN11THEN'Nov'
WHEN12THEN'Dec'
END
+
''+right('0'+cast(day(minimum([DimTime].[Date]for[DimTime].[WeekId])),varchar(2)),2)

Halftodatecurrentyear,prioryear
WhenitisrequestedtogetHalftodate,getreferencedatefirstasdataitem,thengetdatestarted.CYTDCurrentyearto
datePYTDPrioryeartodateCHTDCurrenthalfyeartodatePHTDPriorhalfyeartodate

[DimTime].[Date]between[DateFrom]and[DateTo]

[DateFrom]

casewhen([CurrentMonthNumber]>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([DimTime(Activity)].[CurrentDate])

when(?TimePeriodGrp?='PYTD')then(_add_years([DimTime(Activity)].[CurrentDate],1))

End

{italsocanbedonebydirectlyusingfilter
(([Fact].[DimTime].[CurrentMonthNumber]<7)and([Fact].[DimTime].[Year]=[Fact].[DimTime].[CurrentYear]))
OR
(([Fact].[DimTime].[CurrentMonthNumber]>=7)and([Fact].[DimTime].[Year]=[Fact].[DimTime].[CurrentYear])
and[Fact].[DimTime].[MonthNumber]>=7)
}

7d,MTD,YTD,PYTD

casewhen?RelativeDate?='7d'
then([Date]between_add_days(20070517,7)and(20070517))
when?RelativeDate?='MTD'

http://cognosskills.blogspot.in/

7/13

6/28/2016

CognosSkills
then([Date]between_first_of_month(20070517)and(20070517))
when?RelativeDate?='YTD'
then([Date]between_add_days(20070517,((_day_of_year(20070517)1)*1))
and(20070517))

CurrentYTDSales:
if(SalesDatebetween_make_timestamp(extract(year,current_date),1,1)andcurrent_date)
then(SalesAmount)
else(0)

PriorYTDSales:
if(SalesDatebetween_make_timestamp((extract(year,current_date)1),1,1)and_add_years(current_date,1))
then(SalesAmount)
else(0)

GetLastmonthofdataavailable

assumeavailabledateis[AvailableDate]andtimedimensionis[DimTime]:(year(_add_months(_add_days([Namespace].
[DimTime].[AvailableDate],1),1))*100)+month(_add_months(_add_days([Namespace].[DimTime].[
AvailableDate],1),1))

Getstartdateandenddatebasedonlastavailablemonth

Getyearstartdate

1)_day_of_year([EndDate])
366

2)_add_days([EndDate],_day_of_year([EndDate])+1)
1Jan1212:00:00AM

GetlastcompleteMonthdate

1)[Fact].[DimTime].CurrentDate]
6Jan1312:00:00AM

2)_add_days([Fact].[DimTime].CurrentDate],1)
7Jan1312:00:00AM

3)_add_months(_add_days([Fact].[DimTime].CurrentDate],1),1)
7Dec1212:00:00AM

4)_last_of_month(_add_months(_add_days([Fact].[DimTime].CurrentDate],1),1))
31Dec1212:00:00AM

Getlast13Months

[FactTable].[DimTime].[MonthId]>=

http://cognosskills.blogspot.in/

8/13

6/28/2016

CognosSkills
(year(_add_months(_add_days([FactTable].[DimTime].[CurrentDate],1),13))*100)+
month(_add_months(_add_days([FactTable].[DimTime].[CurrentDate],1),13))and
[FactTable].[DimTime].[MonthId]<=
(year(_add_months(_add_days([FactTable].[DimTime].[CurrentDate],1),1))*100)+
month(_add_months(_add_days([FactTable].[DimTime].[CurrentDate],1),1))

Showdateincrosstab

cast(cast(extract(year,[Returneditems(query)].[Timedimension].[Date]),Char
(4))+substring(cast(cast(_round(((extract(month,[Returneditems(query)].[Time
dimension].[Date])/100)+1)*100,0),integer),Char(3)),2,2)+substring(cast(cast
(_round(((extract(day,[Returneditems(query)].[Timedimension].[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)
)

ForIBMDB2thecalculationshouldlooklikethis:
cast_integer(cast_char(Year([Returneditems(query)].[Timedimension].[Date]),4)

||

right(replace('0'||cast_char(Month([Returneditems(query)].[Timedimension].

[Date]),2),'',''),2)

||

right(replace('0'||cast_char(day([Returneditems(query)].[Timedimension].[Date]),

2),'',''),2))

ForMicrosoftSQLServerthecalculationshouldlooklikethis:
cast_integer(convert({varchar},[Returneditems(query)].[Timedimension].[Date],112))

ForOracle:
to_number(To_Char([Returneditems(query)].[Timedimension].[Date],'YYYYMMDD'))

Usefullinks
CognosTimeandDateFunctionsfromtempleuniversity

FindCurrentPeriodusingclosingPeriodFunction

http://cognosskills.blogspot.in/

9/13

6/28/2016

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

FindCurrentPeriodbyFilteringonMeasureData

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

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

CurrentMonth/Quarter/YTD/TrailingTwelveMonths

Oftenuseabasemonthcurrentperiodtobuildeverythingelseoffof:
[MonthCurrent]=closingPeriod([goc].[Years].[Years].[Month])

Quarter
parent([MonthCurrent])

YTD
total(currentMeasurewithinset
periodsToDate([goc].[Years].[Years].[Year],[MonthCurrent]))

TrailingTwelveMonths
total(currentMeasurewithinset
lastPeriods(12,[MonthCurrent]))

Month%ChangePriorYear
([MonthCurrent][MonthPriorYear])/[MonthPriorYear]
Where[MonthPriorYear]=lag([MonthCurrent],12)

Note:currentMeasureisinthecontextofthecrosstab

Periodtodate

[monthClosingPeriod]=
closingPeriod([GOC].[Years].[Years].[Month])

[periodsToDateForClosingPeriodMonth]=

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

Showrealdatefrompowercube

howtoturncurrentdaytorealdate,butdynamicallydisplayed.

http://cognosskills.blogspot.in/

10/13

6/28/2016

CognosSkills

CurrentDay_Date
descendants([CurrentDay],1)
Yesterday_Date
descendants([Yesterday],1)
Usefullinks
UsingtheperiodsToDatefunctionwithinIBMCognos10ReportStudiotoCalculateanOLAP
RunningTotal
IBMCognos8FrameworkManagerDimensionalModelingforTimePeriodAnalysis

Oracledatefunctions

Getthelastdayoftheweek
selecttrunc(sysdate,'DAY')+6fromdual
Getfirstdayofyear
SELECTTRUNC(TO_DATE('17DEC2001'),'YEAR')"FirstDay"FROMDual
GetlastDayofCurrentMonth
SELECTadd_months(trunc(sysdate)(to_number(to_char(sysdate,'DD'))1),1)1FROMdual

SQLserverdatefunctions

Getthefirstdayofmonth
DATEADD(dd,(DAY(DT.DAY_DT)1),DT.DAY_DT)
Getdatekey
selectcast(convert(varchar(8),getdate(),112)asinteger)
GetlastSunday
Selectcast(convert(varchar(8),dateadd(day,
datepart(weekday,dateadd(WEEK,1,GETDATE()))+1,dateadd(WEEK,1,GETDATE())),112)as
integer)

UsefulQueryitems
1.GettotalremindingtogoforproductCategoryXYZ,set0iftheremindingtogoas0
if(([ProductCategory]='XYZ')
and(total([Forecast]for[ProvinceId],[ProductCategory])
total([Sales]for[ProvinceId],[ProductCategory])>0))

http://cognosskills.blogspot.in/

11/13

6/28/2016

CognosSkills
then
(total([Forecast]for[ProvinceId],[ProductCategory])
total([Sales]for[ProvinceId],[ProductCategory]))
else(0)

2.TYD,QTDandHTDbasedday(Assume[FactCurrentDate],[FactCurrentQuarterNumber]
and[FactCurrentQuarterNumber])
#/*YTDatthebeginingofyear*/#
_add_days([EndDate],_day_of_year([FactTable].[DimTime].[FactCurrentDate])+1)
#/*QTD*/#
if([FactTable].[DimTime].[QuarterId]=[FactTable].[DimTime].[FactCurrentYear]*10+[Fact
Table].[DimTime].[FactCurrentQuarterNumber])
then([FactTable].[FactTable].[Measure])
else(0)
#/*HTD*/#
If([FactTable].[DimTime].[FactCurrentQuarterNumber]>2)Then
(If([FactTable].[DimTime].[QuarterNumber]>2)Then
(If([FactTable].[DimTime].[QuarterId]<=[FactTable].[DimTime].[FactCurrentYear]*10+[Fact
Table].[DimTime].[FactCurrentQuarterNumber])
Then[FactTable].[FactTable].[Measure])
else(0))
Else(0))
Else(
If([FactTable].[DimTime].[QuarterId]<=[FactTable].[DimTime].[FactCurrentYear]*10+[Fact
Table].[DimTime].[FactCurrentQuarterNumber])
then([FactTable].[FactTable].[Measure])
else(0))

Timefilter
filter(
[TimeDimension].[TimeHierarchy].[Date],
roleValue('_businessKey',currentMember([TimeDimension].[TimeHierarchy]))>=
#sq(prompt('From','Date'))#and
roleValue('_businessKey',currentMember([TimeDimension].[TimeHierarchy]))<=#sq(prompt('To',
'Date'))#
)

IdentifyingnthWeekdayofamonthinreports

Requirement:Identifythe2ndThursdayofthecurrentmonth.

Solution:

CreatedataitemsToDate,1stDateofMonth,1stDayofMonth,Nth,Day,AddDays,NthDay

ToDatecurrent_date

1stDateofMonth_first_of_month(ToDate)

1stDayofMonth_day_of_week(1stDateofMonth,1)//AssumingMondayisDay1

Nth2//Thenthvalueoftheweekdayrequired,inourcasewerequire2ndThursday

Day4//AssumingMondayisDay1,thenThursdayisDay4

AddDayscasewhen[Day]>=[1stDayofMonth]
then[Day][1stDayofMonth]

http://cognosskills.blogspot.in/

12/13

6/28/2016

CognosSkills
else
([Day]+[1stDayofMonth])1
end

NthDay_add_days([1stDateofMonth],(([Nth]1)*7)+[AddDay])

NthDayreturnsthe2ndThursdayofthemonth.

Agecalculation
Wehavetwowaystocalculateageinyearsandageinyyyearsmmmonthsanddddaysformat

CalculateAgeinyears...
CreateaqueryCalculationasbelow...
_years_between(current_date,[Birthdatecolumn])
CalculateAgeinyyyears,mmmonthsanddddaysformat...
(replace[BirthDate]withyourownDataofbirthcolumn)

substring(cast(_ymdint_between(current_date,[Birthdate]),char(6)),1,2)||'Years'||
substring(cast(_ymdint_between(current_date,[Birthdate]),char(6)),3,2)
||'months'||
substring(cast(_ymdint_between(current_date,[Birthdate]),char(6)),5,2)
||'Days'

PostedbyDurgaMahaliat03:21

1comment:

Recommend this on Google

Labels:1.BestPracticeinReportStudio,DatefunctionsinReportStudio,daterelatedrelationaland
dimensionalfunctions,ReportStudio:CognosTimeandDateFunctions

Home

OlderPosts

Subscribeto:Posts(Atom)

Simpletemplate.Templateimagesbyluoman.PoweredbyBlogger.

http://cognosskills.blogspot.in/

13/13

You might also like