SQL query result is a two-dimensional table

Source: Internet
Author: User

1 ---Test Data---2 if object_id('[TB]') is  not NULL Drop Table [TB]3 Go4 Create Table [TB]([Code] varchar(6),[Month] int,[Num] int)5 Insert [TB]6 Select 'C00001',200401,3 Union  All7 Select 'C00001',200402,1 Union  All8 Select 'C00001',200403,1 Union  All9 Select 'C00001',200404,3 Union  AllTen Select 'C00001',200405,3 Union  All One Select 'C00001',200604,1 Union  All A Select 'C00002',200401,3 Union  All - Select 'C00002',200402,2 Union  All - Select 'C00002',200404,1 Union  All the Select 'C00002',200405,1 Union  All - Select 'C9999',200401,5 Union  All - Select 'C9999',200402,2 Union  All - Select 'C9999',200403,2 + Go -  + ---Query--- A Declare @sql varchar(8000) at Select  -   @sql=IsNull(@sql+',',"') -   +'sum (case when [month]='+LTrim([Month])+'Then num Else 0 end) as ['+LTrim([Month])+']' -  from -(Select distinct [Month]  fromTB) T -  in exec('Select Code,'+@sql+'From TB GROUP by code') -  to ---Results--- +Code200401      200402      200403      200404      200405      200604 - ------ ----------- ----------- ----------- ----------- ----------- ----------- theC000013           1           1           3           3           1 *C000023           2           0           1           1           0 $C99995           2           2           0           0           0Panax Notoginseng  -(3Row affected)

Original from: https://bbs.csdn.net/topics/350043942

SQL query result is a two-dimensional table

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.