列的“分组依据”之类的东西?

时间:2011-09-19 12:50:45

标签: mysql sql pivot

我有这样的表:

+----+---------+---------+--------+
| id | value_x | created | amount |
+----+---------+---------+--------+

value_x是六个字符串的集合,让我们说“一个”,“两个”,“三个”等。 我需要创建这样的报告:

+--------------+-------------------------+-------------------+----------------------+
| day_of_month |          "one"          |      "two"        |          [etc.]      |
+--------------+-------------------------+-------------------+----------------------+
|  01-01-2011  | "sum(amount) where value_x = colum name" for this specific day     |
+--------------+-------------------------+-------------------+----------------------+

最明显的解决方案是:

SELECT SUM(amount), DATE(created) FROM `table_name` WHERE value_x=$some_variable GROUP BY DATE(created)

并且在每次迭代中使用$some_variable的另一个值循环此查询六次,但是如果可以在单个查询中执行此操作,那么我很有勇气吗?

2 个答案:

答案 0 :(得分:4)

您所询问的内容称为“数据透视表”,通常如下所示。这个想法是针对value_x的每个潜在值,你要么每行产生1或0,要么得到1和0来得到每个值的总和。

SELECT
  DATE(created),
  SUM(CASE WHEN value_x = 'one' THEN SUM(amount) ELSE 0 END) AS 'one',
  SUM(CASE WHEN value_x = 'one' THEN SUM(amount) ELSE 0 END) AS 'two',
  SUM(CASE WHEN value_x = 'one' THEN SUM(amount) ELSE 0 END) AS 'three',
  etc...
FROM table_name
GROUP BY YEAR(created), MONTH(created), DAY(created)

答案 1 :(得分:1)

这将接近:

SELECT
   s.day_of_month
   ,GROUP_CONCAT(CONCAT(s.value_x,':',s.amount) ORDER BY s.value_x ASC) as output
   FROM (
         SELECT DATE(created) as day_of_month
                ,value_x
                ,SUM(amount) as amount
         FROM table1
         GROUP BY day_of_month, value_x
         ) s
GROUP BY s.day_of_month

您需要阅读输出并在value_x之前查找:以将项目放在正确的列中。

这种方法优于@Michael方法的好处是您不需要事先知道字段value_x的可能值。