Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with PIVOT 1

Status
Not open for further replies.

IanWaterman

Programmer
Jun 26, 2002
3,511
GB
I have a PIVOT query which works fine for Year to date.

However, users now want a rolling 12 months pivot

In simplified form my current query looks like

Code:
Select 'DAYS_COUNT' as Measure, [1] as Mth1, [2] as Mth2, [3] as Mth3, [4] as Mth4, [5] as Mth5, .....
from 
(select ID, CalYearNo, CalYearMonthNo from dbo.D_DatePeriod
where CalYearNo = 2014 ) as s
PIVOT
(Count(ID)
FOR  CalYearMonthNo in ([1], [2], [3], [4], [5]...)
) as P

This works fine
However, they now want to change the main query to a range, which rolls forward for each export month

select ID, CalYearNo, CalYearMonthNo from dbo.D_DatePeriod
where date >= '1 March 2013'
and date < '1 March 2014'

I then need to display colums so that 2013-03 = Mth1, 2013-04 = Mth2 etc to 2014-2 Mth12

I assume I also change the PIVOT to
(Count(ID)
FOR date >= '1 March 2013'
and date < '1 March 2014')
) as P

Ideally I should retain the Mth1, Mth2 headers as its going to CSV, but I can live with 2013-03, 2013-04 and sort that out during the export.

THanks for your help

Ian



 
Calyearmonthno for 2013-03 = 3, it will also have a field calyrno = 2013

Ian
 
Try:

Code:
Select 'DAYS_COUNT' as Measure, [1] as Mth1, [2] as Mth2, [3] as Mth3, [4] as Mth4, [5] as Mth5, .....
from 
(
    select ID, DATEDIFF(MONTH, '1 March 2013', DtCadsss) + 1 as CalYearMonthNo 
    from dbo.D_DatePeriod
    where date >= '1 March 2013'
    and date < '1 March 2014'
) as s
PIVOT
(
    Count(ID) FOR CalYearMonthNo in ([1], [2], [3], [4], [5]...)
) as P

Hope this helps.

[URL unfurl="true"]http://www.imoveisemexposicao.com.br/imobiliarias-em-guarulhos[/url]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top