company_name | action | pagecount |
---|---|---|
Company A | 3 | |
Company A | 2 | |
Company A | 3 | |
Company B | ||
Company B | 2 | |
Company B | 2 | |
Company B | 1 | |
Company A | 3 |
Is it possible to run a MySQL query to get output like this:
company_name | PRINT 1 pages | PRINT 2 pages | PRINT 3 pages | |
---|---|---|---|---|
CompanyA | 0 | 0 | 1 | 3 |
CompanyB | 1 | 1 | 2 | 0 |
The idea is that pagecount
can vary so the output column amount should reflect that, one column for each action
/pagecount
pair and then number of hits per company_name
. I’m not sure if this is called a pivot table but someone suggested that?
Many people just use a tool like MSExcel, OpenOffice or other spreadsheet-tools for this purpose. This is a valid solution, just copy the data over there and use the tools the GUI offer to solve this.
But… this wasn’t the question, and it might even lead to some disadvantages, like how to get the data into the spreadsheet, problematic scaling and so on.
The SQL way…
Given his table looks something like this:
Now look into his/her desired table:
The rows (
EMAIL
,PRINT x pages
) resemble conditions. The main grouping is bycompany_name
.In order to set up the conditions this rather shouts for using the
CASE
-statement. In order to group by something, well, use …GROUP BY
.The basic SQL providing this pivot can look something like this:
This should provide the desired result very fast. The major downside for this approach, the more rows you want in your pivot table, the more conditions you need to define in your SQL statement.
This can be dealt with, too, therefore people tend to use prepared statements, routines, counters and such.
Some additional links about this topic: