PHP mysql与变量字段交叉

时间:2013-02-20 21:46:10

标签: php mysql

我正在努力制作数据透视表/交叉表。最后我想内联编辑它,但首先我想至少制作表格。

在表'tarifs'中我有一个Id,TarifCode和TarifDescr 像:

1, A, Overnight
2, P, Room
3, V, Adult No discount
etc.

在我的申请中的某个时刻,我会填写开始日期,结束日期和适用的tarifcodes值(金额)。 喜欢:

2012-02-05, 2012-02-09, A:1, P:0, V:2

提交SQL查询后填写表'Occupacion',即存在ID,Date,TarifCode,Value,如:

1, 2012-02-05, A, 1
2, 2012-02-05, V, 2
3, 2012-02-06, A, 1
4, 2012-02-06, V, 2
5, 2012-02-07, A, 1
6, 2012-02-07, V, 2
7, 2012-02-08, A, 1
8, 2012-02-08, V, 2
9, 2012-02-09, A, 1
10, 2012-02-09, V, 2

这是我的问题: 如何创建一个查询(或视图),为我提供下一个输出:

-- 2012-02-05 | 2012-02-06 | 2012-02-07 | 2012-02-08 | 2012-02-09
A           1            1            1            1            1
V           2            2            2            2            2

在与此主题相关的大多数帖子中,值都是已知的。在我的情况下,有时没有使用TarifCode A或者创建了新的TarifCode。

最后我想以JSON风格制作这个,所以我可以用它在网格中进行内联编辑。也许有人有经验吗?

1 个答案:

答案 0 :(得分:0)

如果您想使用SQL执行此操作,那么您可以使用聚合函数和CASE表达式转发 MySQL中的数据。这将获取date值并将其转换为列:

select tarifcode,
  max(case when Date = '2012-02-05' then value end) `2012-02-05`,
  max(case when Date = '2012-02-06' then value end) `2012-02-06`,
  max(case when Date = '2012-02-07' then value end) `2012-02-07`,
  max(case when Date = '2012-02-08' then value end) `2012-02-08`,
  max(case when Date = '2012-02-09' then value end) `2012-02-09`
from yourtable
group by tarifcode

请参阅SQL Fiddle with Demo

如果日期未知,那么您可以使用类似于此的准备语句:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when Date = ''',
      Date,
      ''' then value end) AS `',
      Date, '`'
    )
  ) INTO @sql
FROM  yourtable;

SET @sql = CONCAT('SELECT TarifCode, ', @sql, ' 
                  FROM yourtable 
                  GROUP BY TarifCode');

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

SQL Fiddle with Demo。两个查询的结果是:

| TARIFCODE | 2012-02-05 | 2012-02-06 | 2012-02-07 | 2012-02-08 | 2012-02-09 |
------------------------------------------------------------------------------
|         A |          1 |          1 |          1 |          1 |          1 |
|         V |          2 |          2 |          2 |          2 |          2 |

编辑,如果你想加入另一个表,那么你可以使用类似的东西:

select 
  t.tarifcode,
  max(case when Date = '2012-02-05' then value end) `2012-02-05`,
  max(case when Date = '2012-02-06' then value end) `2012-02-06`,
  max(case when Date = '2012-02-07' then value end) `2012-02-07`,
  max(case when Date = '2012-02-08' then value end) `2012-02-08`,
  max(case when Date = '2012-02-09' then value end) `2012-02-09`
from tarifs t
left join yourtable y
  on t.tarifcode = y.tarifcode
group by t.tarifcode

请参阅SQL Fiddle with Demo