如何计算年份和价值?

时间:2014-01-27 06:57:38

标签: mysql sql select group-by pivot

我有一些结果用于此查询,但我想改变下面的结果

而不是它

结果显示::

    2011                     2012
    26267.620000000003       404603.20999999996
    144384.36                173245.96000000002 
    199704.47999999998       208524.42

查询

SELECT
    YEAR (PAYMENTDATE) AS YEARNUMBER,
    MONTH (PAYMENTDATE) AS MONNUMBER,
    SUM (AMOUNT) AS MONTOTAL
    FROM 
    PAYMENTS
    GROUP BY 
    YEAR (PAYMENTDATE)

结果::用于上述查询

2011        26267.620000000003  
2011        144384.36   
2012        173245.96000000002  
2012        208524.42

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT MONNUMBER, 
       MAX(CASE WHEN YEARNUMBER = 2011 THEN MONTOTAL ELSE 0 END) AS Year2011,
       MAX(CASE WHEN YEARNUMBER = 2012 THEN MONTOTAL ELSE 0 END) AS Year2011
FROM (SELECT YEAR(PAYMENTDATE) AS YEARNUMBER, MONTH(PAYMENTDATE) AS MONNUMBER, 
             SUM(AMOUNT) AS MONTOTAL
      FROM PAYMENTS
      GROUP BY YEAR(PAYMENTDATE)
    ) AS A
GROUP BY MONNUMBER