Google
 

Thursday, October 4, 2007

UNPIVOT

For certain source systems like AccPac, you may need to convert your column-based list of periods or months into a row-based list that is friendlier for an OLAP data model with a time dimension.

The SQL 2000 solution would be to use a case statement or possibly a custom pivot function, or maybe some creative use of the isnull function.

Here is an example query for this in SQL 2005: 

SELECT
[ACCTID]
,[FSCSYR]
,[FSCSDSG]
,[FSCSCURN]
,[CURNTYPE]
,[AUDTDATE]
,[AUDTTIME]
,[AUDTUSER]
,[AUDTORG]
,[SWRVL]
,[CODERVL]
,[SCURNDEC]
,[OPENBAL]
,[PERIOD], Balance
FROM
(
SELECT [ACCTID]
,[FSCSYR]
,[FSCSDSG]
,[FSCSCURN]
,[CURNTYPE]
,[AUDTDATE]
,[AUDTTIME]
,[AUDTUSER]
,[AUDTORG]
,[SWRVL]
,[CODERVL]
,[SCURNDEC]
,[OPENBAL]
,[NETPERD1] [Jan]
,[NETPERD2] [Feb]
,[NETPERD3] [Mar]
,[NETPERD4] [Apr]
,[NETPERD5] [May]
,[NETPERD6] [Jun]
,[NETPERD7] [Jul]
,[NETPERD8] [Aug]
,[NETPERD9] [Sep]
,[NETPERD10] [Oct]
,[NETPERD11] [Nov]
,[NETPERD12] [Dec]
,[NETPERD13]
,[NETPERD14]
,[NETPERD15]
,[ACTIVITYSW]
FROM [GLAFS]
WHERE activitysw = 1 ) Balance

UNPIVOT (
Balance
FOR [Period]

IN ( [Jan], [Feb], [Mar], [Apr],
[May], [Jun], [Jul], [Aug],
[Sep], [Oct], [Nov], [Dec])
) AS unpvt
WHERE BALANCE <> 0

No comments: