Skip to main content

SQL - Pivoting / CrossTabs

The PIVOTRESULTSET extension is used to convert linear data into a Cross Tab. Cross tabs are still limited to the 32 column maximum of an SQL Result Set.

For example, the following SQL would produce the following result:

SELECT Account,Month,Amount

FROM CUSTOMERS

ORDER BY ACCOUNT,MONTH
AccountMonthAmount
1011$10.00
1012$20.00
1013$30.00
1021$11.00
1022$21.00
1023$31.00
1031$1.00
1032$2.00
1033$3.00

For example, the following SQL with the PIVOTRESULTSET WITHTOTALS would produce the following result:

SELECT Account,Month,Amount

FROM CUSTOMERS

ORDER BY ACCOUNT,MONTH

PIVOTRESULTSET WITHTOTALS
Account123Total
101$10.00$20.00$30.00$60.00
102$11.00$21.00$31.00$63.00
103$1.00$2.00$3.00$6.00
Total:$22.00$43.00$64.00$129.00

To use PIVIOTRESULTSET, there must be at least 3 columns of data and no more than 8 columns of data in your SQL Query.

  • The last column is the data that will be plotted. (AMOUNT)
  • The second to last column will be Column Headers. (MONTH)
  • All unused columns will show on each detail line, up to 5. (ACCOUNT)

In this example, the following SQL with the PIVOTRESULTSET WITHTOTALS would produce the following result:

SELECT Account,AccountName,MONTH,AMOUNT

FROM CUSTOMERS

ORDER BY ACCOUNT,MONTH

PIVOTRESULTSET WITHTOTALS
AccountAccountName123Total
101Oranges$10.00$20.00$30.00$60.00
102Apples$11.00$21.00$31.00$63.00
103Bananas$1.00$2.00$3.00$6.00
Total:$22.00$43.00$64.00$129.00

Note that any data which is non-existent for a particular cell will show up as Blank, not formatted as 0.00 or 0.

You can use PIVOTRESULTFIELDS to dictate the order of the column headers. This is only needed if not all rows have the same number of columns and the columns should appear in a certain order, such as Months.

In this example, the months January through May will appear at the beginning, regardless of if the first row has data for January through May.

SELECT Account,AccountName,MONTH,AMOUNT

FROM CUSTOMERS

ORDER BY ACCOUNT,MONTH

PIVOTRESULTSET WITHTOTALS

PIVOTRESULTFIELDS 1,2,3
AccountAccountName123Total
101Oranges$30.00$60.00
102Apples$11.00$21.00$31.00$63.00
103Bananas$1.00$2.00$3.00$6.00
Total:$22.00$43.00$64.00$129.00
SELECT Account,AccountName,MONTHNAME(MONTH) ,AMOUNT

FROM CUSTOMERS

ORDER BY ACCOUNT,MONTH

PIVOTRESULTSET WITHTOTALS

PIVOTRESULTFIELDS January,February,March
AccountAccountNameJanuaryFebruaryMarchTotal
101Oranges30.00$60.00
102Apples$11.00$21.00$31.00$63.00
103Bananas$1.00$2.00$3.00$6.00
Total:$22.00$43.00$64.00$129.00