How to generate the output of a pivot table in MySQL?
P粉180844619
2023-08-22 10:54:31
If I have a MySQL table like this:
<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>
Is it possible to run a MySQL query to get output like this:
<pre>company_name EMAIL PRINT 1 page PRINT 2 pages PRINT 3 pages
-------------------------------------------------- ----------
CompanyA 0 0 1 3
CompanyB 1 1 2 0
</pre>
The idea is that <code>pagecount</code> may change, so the number of columns in the output should reflect this, one column for each <code>action</code>/<code>pagecount</code> , and then count the number of hits for each <code>company_name</code>. I'm not sure if this is called a pivot table, but someone suggested this
My solution is to use T-SQL without any pivot:
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 adapting this solution to your needs.
renew
Since the link above is currently no longer available, I feel obligated to provide some additional information for anyone looking for answers to mysql pivot tables here. It does have a ton of information, and I won't copy everything here (not to mention I don't want to copy their vast knowledge), but I will give some advice on how to work with pivot tables using SQL, and first Example of peku that asked the question.
Maybe the link will come back soon, I'll keep an eye out.
Spreadsheet method...
Many people just use spreadsheet tools like MSExcel, OpenOffice or other to accomplish this purpose. 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 shortcomings, such as how to import data into spreadsheets, scalability issues, etc.
SQL way...
Suppose his table looks like this:
Now look at the table he/she expects:
Theline (
EMAIL
,PRINT x pages
) represents the condition. The main grouping is bycompany_name
.In order to set conditions, it is more appropriate to use the
CASE
statement. To group by something, use...GROUP BY
.The basic SQL to provide this pivot table might be like this:
This should provide the desired results very quickly. The main disadvantage of this approach is that the more rows you need in the pivot table, the more conditions you need to define in the SQL statement.
This can also be solved, so people tend to use prepared statements, routines, counters, etc.
Some additional links on this topic: