How to return the output of a pivot table in MySQL?
P粉578343994
2023-07-25 13:59:22
<p>If I have a MySQL table like this: </p>
<pre>company_name action pagecount
----------------------------------
COMPANY A PRINT 3
COMPANY A PRINT 2
COMPANY A PRINT 3
Company BEMAIL
Company B PRINT 2
Company B PRINT 2
COMPANY B PRINT 1
COMPANY A PRINT 3
</pre>
<p>Can you run a MySQL query to get the following output: </p>
<pre>company_name EMAIL PRINT 1 pages PRINT 2 pages PRINT 3 pages
-------------------------------------------------- ----------
CompanyA 0 0 1 3
CompanyB 1 1 2 0
</pre>
<p>The idea is that the page count can vary, so the number of columns in the output should reflect this, with one column for each action/page count, and then count the number of clicks for each company name. I'm not sure if this is called a pivot table, but someone has suggested doing this. </p>
My solution is to use T-SQL instead of any pivot table:
This is basically a pivot table.
A detailed tutorial on how to implement this can be found here: http://www.artfulsoftware.com/infotree/qrytip.php?id=78
I recommend reading this article, and adjust it to your own needs.
UPDATE
Since the link above is currently no longer available, I felt it necessary to provide some additional information for anyone looking for answers to MySQL Pivot Tables here. This link really has a lot of information, I'm not going to copy it all (and I don't want to copy their wealth of knowledge), but I will give some advice on how to work with pivot tables in SQL, with peku Take the question posed as an example.
Maybe the link will be restored soon, I will keep an eye on it.
The spreadsheet way...
Many people just use tools like MSExcel, OpenOffice or other spreadsheet tools to accomplish this task. This is a valid solution, just copy the data there and use the tools provided by the GUI to solve the problem.
But... this is not the crux of the problem, and may even lead to some disadvantages, such as how to import data into spreadsheets, scalability issues, etc.
SQL way...
Suppose his table looks like this:
Now look at the expected table:
Theline (EMAIL, print x pages) is similar to a condition. The main grouping is by company name.
In order to set conditions, it is more suitable to use the CASE statement. In order to group by something, you can use GROUP BY.
The basic SQL statement that provides this pivot table might look like this:
This should provide the desired results very quickly. The main disadvantage of this approach is that the more rows you want to have in the pivot table, the more conditions you need to define in the SQL statement.
This problem can also be solved, so people tend to use prepared statements, routines, counters, etc.
Here are some additional links on this topic: