SQL Server PIVOT Usage Example

Source: Internet
Author: User

Recently learned the new features of SQL 2005, probably a lot of people know, I am relatively slow, after two days are 2010 years, before I began to learn 2005. To sum up:

The table is as follows:

CREATE TABLE TB (ID varchar (m), CName varchar (), Amount money,actiondate datetime)

INSERT into TB values (' 001 ', ' A ', 2000.00, ' 2008-02-28 ')

INSERT into TB values (' 001 ', ' A ', 1560.00, ' 2008-03-28 ')

INSERT into TB values (' 001 ', ' A ', 2040.00, ' 2008-01-28 ')

INSERT into TB values (' 001 ', ' A ', 1003.00, ' 2008-04-28 ')

INSERT into TB values (' ' ', ' B ', 3100.00, ' 2008-03-28 ')

INSERT into TB values (' ' ', ' B ', 4040.00, ' 2008-01-28 ')

INSERT into TB values (' ' ', ' B ', 5003.00, ' 2008-04-28 ')

INSERT into TB values (' ' ', ' B ', 2400.00, ' 2008-02-28 ')

INSERT into TB values (' 001 ', ' A ', 15000.00, ' 2007-12-21 ')

INSERT into TB values (' ' ', ' B ', 22400.00, ' 2007-12-21 ')

---------to convert the data into the following:

ID CName 2007-12 2008-01 2008-02 2008-03 2008-04

001 a 15000.00 2040.00 2000.00 1560.00 1003.00

b 22400.00 4040.00 2400.00 3100.00 5003.00

The implementation steps are as follows:

-----

Select Id,cname,sum (amount) as amount,left (CONVERT (varchar, actiondate,120), 7) as Actiondate

Into #tmp

From TB

Group BY Id,cname,left (CONVERT (varchar, actiondate,120), 7)

DECLARE @sql varchar (max), @sqlAll nvarchar (max)

Select @sql = '

Select @sql = @sql + ' [' +actiondate+ '], '

From #tmp GROUP by actiondate

Select @sql =left (@sql, Len (@sql)-1)

Print @sql

Select @sqlAll = '

SELECT * FROM #tmp s

Pivot

(Sum (amount)

For actiondate in (' + @sql + ')

As P order by Id,cname '

Print @sqlAll

------STEP4

EXEC sp_executesql @sqlAll

drop table #tmp

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.