如何以某种方式在select中做一个循环?

时间:2013-04-19 06:50:49

标签: mysql sql pivot

我有这张桌子。

+------+-------+--------+
| CODE | MONTH | AMOUNT |
+------+-------+--------+
|    2 |     1 |    100 |
|    3 |     1 |    200 |
|    2 |     2 |    300 |
|    3 |     2 |    400 |
+------+-------+--------+

而且,这是我想要的结果。

+------+---------+---------+
| CODE |     MO1 |     MO2 |
+------+---------+---------+
|    2 |     100 |     300 |
|    3 |     200 |     400 |
+------+---------+---------+

我知道在select中循环是不可能的。
我想我可以使用CASE,但我没有明确的数月 如上例所示,其中只有1月份的数据 和二月我将在3月份获得数据。我怎么能这样做?

2 个答案:

答案 0 :(得分:5)

由于你不知道几个月的确定数量,你可以动态地这样做:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(case when Month = ''',
      Month,
      ''' then Amount else 0 end) AS `Mo',
      Month, '`'
    )
  ) INTO @sql
FROM Table2;


SET @sql = CONCAT('SELECT Code, ', @sql, '
                  FROM Table2 
                  GROUP BY Code');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

结果:

| CODE | MO1 | MO2 |
--------------------
|    2 | 100 | 300 |
|    3 | 200 | 400 |

See this SQLFiddle

答案 1 :(得分:0)

SELECT A.CODE AS CODE, A.AMOUNT as MO1, B.AMOUNT as MO2 FROM
((SELECT CODE, AMOUNT from Table1 WHERE MONTH=1) AS A
INNER JOIN
(SELECT CODE, AMOUNT from Table1 WHERE MONTH=2) AS B
ON
A.CODE=B.CODE)

如果超过2个月,则添加更多内部联接

希望这会有所帮助:)