Frequently used cross tabulation problems. Dynamic SQL statements can generate dynamic columns! _ PHP Tutorial

Source: Internet
Author: User
Cross tabulation is frequently used. Dynamic columns can be generated using dynamic SQL !. Original table format: ClassCallDateCallCount12005-8-84012005-8-7622005-8-87732005-8-93332005-8-8932005-8-721 according to the value of Class, respectively according to the date CallC original table format:
Class CallDate CallCount
1 2005-8-8 40
1 2005-8-7 6
2 2005-8-8 77
3 2005-8-9 33
3 2005-8-8 9
3 2005-8-7 21
CallCount1, CallCount2, and CallCount3 are calculated by date based on the Class values.
When no record value for this date is set to 0
Merge the data into the following format:
CallDate CallCount1 CallCount2 CallCount3
2005-8-9 0 0 33
2005-8-8 40 77 9
2005-8-7 6 0 21
-- Create a test environment
Create table T (Class varchar (2), CallDate datetime, CallCount int)
Insert into T select '1', '2017-8-8 ', 40
Union all select '1', '2014-8-7 ', 6
Union all select '2', '2017-8-8 ', 77
Union all select '3', '2014-8-9 ', 33
Union all select '3', '2017-8-8', 9
Union all select '3', '2014-8-7 ', 21
-- Dynamic SQL
Declare @ s varchar (8000)
Set @ s = 'SELECT calldate'
Select @ s = @ S', [CallCount 'class'] = sum (case when Class = '''class''' then CallCount else 0 end )'
From T
Group by Class
Set @ s = @ s' from T group by CallDate order by CallDate desc'
Exec (@ s)
-- Result
CallDate CallCount1 CallCount2 CallCount3
---------------------------------------------------------------------------------------
2005-08-09 00:00:00. 000 0 0 33
00:00:00. 000 40 77 9
2005-08-07 00:00:00. 000 6 0 21
-- Delete the Test environment
Drop table T


Keep Class CallDate CallCount 1 2005-8-8 40 1 2005-8-7 6 2 2005-8-8 77 3 2005-8-9 33 3 2005-8-8 9 3 2005-8-7 21 according to the Class value, calculate CallC by date...

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.