Sample Code for SQL multi-table row-to-column and cascading row-to-column Conversion

Source: Internet
Author: User

Two existing tables A and B

Table A stores product click logs, and table B stores products.

Display the clicks list of all items on the current day with the total number and sort by day
Copy codeThe Code is as follows:
Declare @ SQL varchar (2000)
Set @ SQL = 'select CONVERT (varchar (100), a. [Time], 23) as Time, count (B. title) as total'
Select @ SQL = @ SQL + ', sum (case B. title when ''' + Title + ''' then 1 else 0 end) as '+' ['+ Title +']'
From (select distinct title from B) as B
Set @ SQL = @ SQL + 'from A as a left join B as B on a. AId = B. Aid
Group by CONVERT (varchar (100), a. [Time], 23) order by CONVERT (varchar (100), a. [Time], 23) desc'
Exec (@ SQL)

Display result

Time Total Item 1 Product 2 Item 3
5 1 0 4
13 2 11 1

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.