Friday, February 24, 2012

Crosstab queries

Dear friends,

I wonder if exist a way to make crosstab queries in SQL Server
like those in Access without "external" programming. Does the
SQL Server supports the "TRANSFORM" SQL-extension?

Thanks in advance, Sotiris.Sotiris Rentoulis (rentoulis@.hotmail.com) writes:
> I wonder if exist a way to make crosstab queries in SQL Server
> like those in Access without "external" programming. Does the
> SQL Server supports the "TRANSFORM" SQL-extension?

No.

There is no particular support for pivot tables in SQL 2000. SQL 2005,
currently in beta, comes with a PIVOT operator. It still only supports
static pivot tables.

Here is a simple example of a static crosstab in SQL 2000:

SELECT product,
Q1 = SUM(CASE datepart(month, salesdate) / 3 WHEN 0 THEN amt END),
Q2 = SUM(CASE datepart(month, salesdate) / 3 WHEN 1 THEN amt END),
Q3 = SUM(CASE datepart(month, salesdate) / 3 WHEN 2 THEN amt END),
Q4 = SUM(CASE datepart(month, salesdate) / 3 WHEN 3 THEN amt END)
FROM sales
GROUP BY product

Dynamic crosstabs requires you to write dynamic SQL. Note that dynamic
crosstabs, how useful they be, do not really fit into the relational
model. A popular tool for dynamic crosstab is RAC, see
http://www.rac4sql.net.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

No comments:

Post a Comment