//  home   //  advanced search   //  news   //  categories   //  sql build chart   //  downloads   //  statistics
 ASP FAQ 
Home
ASP FAQ Tutorials

   8000XXXX Errors
   ASP.NET 2.0
   Classic ASP 1.0
   Databases
      Access DB & ADO
      General SQL Server & Access Articles
      MySQL
      Other Articles
      Schema Tutorials
      Sql Server 2000
      Sql Server 2005
   General Concepts
   Search Engine Optimization (SEO)

Contact Us
Site Map

Search

Web
aspfaq.com
tutorials.aspfaq.com
sqlserver2000.databases.aspfaq.com

ASP FAQ Tutorials :: Databases :: Sql Server 2000 :: How do I create a cross-tab (or "pivot") query?


How do I create a cross-tab (or "pivot") query?

You may find that your data is not well-suited for what you might term as pivot or cross-tab reports. Now, while I believe that such pivoting functionality belongs at the presentation tier and not the data tier, there are many ways to generate reports like this. Here is a simple example that takes normalized sales figures by year and quarter, and produces one row and four columns per year. Run this in Query Analyzer and the output should be pretty self-explanatory: 
 
SET ANSI_WARNINGS OFF 
SET NOCOUNT ON 
 
CREATE TABLE dbo.SalesByQuarter 

    Y INT, 
    Q INT, 
    sales INT, 
    PRIMARY KEY (Y,Q) 

GO 
 
INSERT dbo.SalesByQuarter(Y,Q,Sales) 
    SELECT 2003, 2, 479000 
    UNION SELECT 2003, 3, 321000 
    UNION SELECT 2003, 4, 324000 
    UNION SELECT 2004, 1, 612000 
    UNION SELECT 2004, 2, 524000 
    UNION SELECT 2004, 3, 342000 
    UNION SELECT 2004, 4, 357000 
    UNION SELECT 2005, 1, 734000 
GO 
 
SELECT Y,  
    Q1 = SUM(CASE WHEN Q=1 THEN Sales END), 
    Q2 = SUM(CASE WHEN Q=2 THEN Sales END), 
    Q3 = SUM(CASE WHEN Q=3 THEN Sales END), 
    Q4 = SUM(CASE WHEN Q=4 THEN Sales END) 
FROM 
    dbo.SalesByQuarter 
GROUP BY Y 
ORDER BY Y 
GO 
 
DROP TABLE dbo.SalesByQuarter 
GO
 
SQL Server 2005 introduces the new PIVOT keyword, however I think it will be a disappointment to most. What people have been searching for is a very dynamic way to pivot, so that you don't have to know all of the potential column headers beforehand. Again, I still feel that the best place to rotate this data is on the client. But I know that some people out there are stubborn and/or don't understand the difference. 
 
In any case, here is the above query in SQL Server 2005 style: 
 
CREATE TABLE dbo.SalesByQuarter 

    Y INT, 
    Q INT, 
    sales INT, 
    PRIMARY KEY (Y,Q) 

GO 
 
INSERT dbo.SalesByQuarter(Y,Q,Sales) 
    SELECT 2003, 2, 479000 
    UNION SELECT 2003, 3, 321000 
    UNION SELECT 2003, 4, 324000 
    UNION SELECT 2004, 1, 612000 
    UNION SELECT 2004, 2, 524000 
    UNION SELECT 2004, 3, 342000 
    UNION SELECT 2004, 4, 357000 
    UNION SELECT 2005, 1, 734000 
GO 
 
SELECT Y,  
    [1] AS Q1, 
    [2] AS Q2, 
    [3] AS Q3, 
    [4] AS Q4 
FROM 
    (SELECT Y, Q, Sales 
        FROM SalesByQuarter) s 
PIVOT 

    SUM(Sales) 
    FOR Q IN ([1],[2],[3],[4]) 
) p 
ORDER BY [Y] 
GO 
 
DROP TABLE dbo.SalesByQuarter 
GO
 

Now, you may want to do something more complex, or as mentioned above, produce results a little more dynamically based on the data. Here are some links to code samples: 
 
    Dynamic Crosstab Queries 
 
    Microsoft SQL Server - Dynamic Cross-Tab... 
 
    A simple way to perform crosstab operati... 
 
There are also some third party applications available to ease the work required (and surely Crystal Reports and Excel could be programmed to handle this case as well): 
 
    Rac for SQL2K 
 
    Sql.Net 
 
    The Query Tool 
 
    xp_ags_crosstab 
 
If you know of others, please let us know so we can add them to our list. 

Related Articles

Are there tools available for auditing changes to SQL Server data?
Can I create an index on a BIT column?
Can I have optional parameters to my stored procedures?
Can I implement an input mask in SQL Server?
Can I make SQL Server format dates and times for me?
Can I start IDENTITY values at a new seed?
Can SQL Server tell me which row was inserted most recently?
How can I learn more about undocumented SQL Server stored procedures?
How can I make my SQL queries case sensitive?
How do I audit changes to SQL Server data?
How do I connect to a non-default instance of SQL Server?
How do I connect to SQL Server on a port other than 1433?
How do I determine if a table exists in a SQL Server database?
How do I drop a SQL Server database?
How do I find all the available SQL Servers on my network?
How do I get a list of SQL Server tables and their row counts?
How do I get rid of Named Pipes / DBNMPNTW errors?
How do I get the correct date/time from the msdb.sysjob* tables?
How do I get the nth row in a SQL Server table?
How do I get the result of dynamic SQL into a variable?
How do I handle REPLACE() within an NTEXT column in SQL Server?
How do I hide system tables in SQL Server's Enterprise Manager?
How do I know which version of SQL Server I'm running?
How do I limit the number of rows returned in my resultset?
How do I load text or csv file data into SQL Server?
How do I manage changes in SQL Server objects?
How do I monitor SQL Server performance?
How do I prevent linked server errors?
How do I reclaim space in SQL Server?
How do I recover data from SQL Server's log files?
How do I search for special characters (e.g. %) in SQL Server?
How do I start SQL Server Agent from ASP?
How do I time my T-SQL code?
How do I upsize from Access to SQL Server?
How do I upsize my MSDE database to full-blown SQL Server 2000?
How do I use a variable in a TOP clause in SQL Server?
How do I use GETDATE() within a User-Defined Function (UDF)?
How should I store an IP address in SQL Server?
Schema: How do I find all the foreign keys in a database?
SQL Server & MSDE
What are reserved Access, ODBC and SQL Server keywords?
What are the capacities of Access, SQL Server, and MSDE?
What are the main differences between Access and SQL Server?
What do I need to know about SQL Server 2000 SP4?
Where else can I learn about SQL Server?
Where is SP4 for SQL Server 2000?
Why am I having problems with SQL Server 2000 SP3 / SP3a?
Why can't I install SQL Server on Windows Server 2003?
Why can't I install SQL Server on Windows XP?
Why can't I use LIKE '%datepart%' queries?
Why do I get "Login failed for user '\'."?
Why do I get 'object could not be found' or 'invalid object name'?
Why do I get errors about master..spt_values?
Why do I get script errors in Enterprise Manager's 'taskpad' view?
Why do I get SQLSetConnectAttr Failed errors?
Why do I have problems with views after altering the base table?
Why does EM crash when I get an error in a stored procedure?
Why does Enterprise Manager return 'Invalid cursor state'?
Why does my DELETE query not work?
Why does sp_spaceused return inaccurate values?
Why is Enterprise Manager slow at expanding my database list?
Why is my app slow after upgrading from SQL Server 7 to 2000?
Why is tempdb full, and how can I prevent this from happening?
Why should I consider using an auxiliary calendar table?
Why should I consider using an auxiliary numbers table?

 

 


Created: 6/22/2003 | Last Updated: 6/4/2006 | broken links | helpful | not helpful | statistics
© Copyright 2006, UBR, Inc. All Rights Reserved. (187)

 

Copyright 1999-2006, All rights reserved.
Finding content
Finding content.  An error has occured...