Note that there are some explanatory texts on larger screens.

plurals
  1. POCreate a Summary View in MySQL by pivoting row into dynamic number of columns
    primarykey
    data
    text
    <p>I have a table in MySQL with the following fields:</p> <pre><code>id, company_name, year, state </code></pre> <p>There are multiple rows for the same customer and year, here is an example of the data:</p> <pre><code> id | company_name | year | state ---------------------------------------- 1 | companyA | 2008 | 1 2 | companyB | 2009 | 2 3 | companyC | 2010 | 3 4 | companyB | 2009 | 1 5 | companyC | NULL | 3 </code></pre> <p>I am trying to create a view from this table to show one company per row (i.e. <code>GROUP BY</code> pubco_name) where the state is the highest for a given year.</p> <p>Here is an example of the view I am trying to create:</p> <pre><code> id | cuompany_name | NULL | 2008 | 2009 | 2010 -------------------------------------------------- 1 | companyA | NULL | 1 | NULL | NULL 2 | companyB | NULL | 2 | NULL | NULL 3 | companyC | 3 | NULL | NULL | 3 </code></pre> <p>There is a lot more data than this, but you can see what I am trying to accomplish.</p> <p>I don't know how to select the max state for each year and group by pubco_name. Here is the SQL I have thus far (I think we need to use <code>CASE</code> and/or <code>sub-selects</code> here):</p> <pre><code>SELECT id, company_name, SUM(CASE WHEN year = 2008 THEN max(state) ELSE 0 END) AS 2008, SUM(CASE WHEN year = 2009 THEN max(state) ELSE 0 END) AS 2009, SUM(CASE WHEN year = 2010 THEN max(state) ELSE 0 END) AS 2010, SUM(CASE WHEN year = 2011 THEN max(state) ELSE 0 END) AS 2011, SUM(CASE WHEN year = 2012 THEN max(state) ELSE 0 END) AS 2012, SUM(CASE WHEN year = 2013 THEN max(state) ELSE 0 END) AS 2013 FROM tbl GROUP BY company_name ORDER BY id DESC </code></pre> <p>Appreciate your help and thanks in advance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload