title: Using a variable/function as a dynamic column name in MySQL
body: <p>Is it possible to use a function or a variable as the label for a column in MySQL?</p>
  
  <p>So for example if you wanted to include the date, something like:</p>
  
  <pre><code>select 
    sum(P.AMOUNT) AS monthname(date_sub(CURDATE(), INTERVAL 1 MONTH))
  from
    PAYMENT P
  WHERE
    P.CREATED_DATE &gt; (date_sub(CURDATE(), INTERVAL 1 MONTH));
  </code></pre>
  
  <p>This fails, as it's not the correct syntax for an AS alias. I've also tried this:</p>
  
  <pre><code>SET @s = monthname(date_sub(CURDATE(), INTERVAL 1 MONTH));
  
  select 
    sum(P.AMOUNT) AS @s
  from
    PAYMENT P
  WHERE
    P.CREATED_DATE &gt; (date_sub(CURDATE(), INTERVAL 1 MONTH)); 
  </code></pre>
  
  <p>Which also doesn't work...</p>
  
  <p>Any ideas?</p>
  
  <p>EDIT - With the above example i realize you could actually just use an additional column to return the date info. The problem is i have a few columns with various date ranges, like this:</p>
  
  <pre><code>select
    sum(IF((P.CREATED_DATE BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 MONTH) and DATE_SUB(CURDATE(), INTERVAL 0 MONTH)),P.amount,0)) AS 'Month 0',
    sum(IF((P.CREATED_DATE BETWEEN DATE_SUB(CURDATE(), INTERVAL 2 MONTH) and DATE_SUB(CURDATE(), INTERVAL 1 MONTH)),P.amount,0)) AS 'Month -1',
    sum(IF((P.CREATED_DATE BETWEEN DATE_SUB(CURDATE(), INTERVAL 3 MONTH) and DATE_SUB(CURDATE(), INTERVAL 2 MONTH)),P.amount,0)) AS 'Month -2'
  from
    PAYMENT P
  WHERE
    P.AMOUNT &lt; 100000;
  </code></pre>
  
  <p>So it's the "Month 0" etc i'm looking to replace with a function/query. </p>