如何在动态数据透视表上显示最小值和最大值

时间:2016-05-05 02:58:14

标签: mysql pivot-table

我使用dt_k

从dt_table join创建了一个数据透视表
table dt_k
+------+--------+-----+
| id_k | name_k | ott |
+------+--------+-----+
|  1   | item 1 | ss  |
|  2   | item 2 | ss  |
|  3   | item 3 | ww  |
|  4   | item 4 | dd  |
|  5   | item 5 | asa |
|  6   | item 6 | rr  |
+------+--------+-----+

dt_table
+------+--------+------+----+
| id_t |  id_u  | id_k | k  |
+------+--------+------+----+
|  1   |   22   |  1   | 2  |
|  2   |   22   |  2   | 3  |
|  3   |   22   |  3   | 23 |
|  4   |   22   |  4   | 4  |
|  5   |   22   |  6   | 34 |
|  6   |   24   |  1   | 23 |
|  7   |   24   |  2   | 34 |
|  8   |   24   |  3   | 54 |
|  9   |   24   |  4   | 21 |
| 11   |   24   |  6   | 44 |
+------+--------+------+----+

我使用数据透视表将行转换为列,这是我的代码:

SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
  'max(case when col = ''',
  col,
  ''' then value end) as `', 
  col, '`')
) INTO @sql
FROM
(
select concat('op_', `id_k`) col
from dt_table

) d;
SET @sql = CONCAT('SELECT  d.id_u as id,', @sql, ' 
              from
              (
                select id_k, id_u, concat(''op_'', `id_k`) col,  k value
                from dt_table

              ) d group by id_u ');


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

此代码提供如下结果

+------+------+------+------+------+------+
| id_u | op_1 | op_2 | op_3 | op_4 | op_6 |
+------+------+------+------+------+------+
|  22  |   2  |  3   |  23  |  4   |  34' |
|  24  |  23  |  34  |  54  |  21  |  44  |
+------+------+------+------+------+------+

我需要此表显示每列上的最小值和最大值

+------+------+------+------+------+------+
| id_u | op_1 | op_2 | op_3 | op_4 | op_6 |
+------+------+------+------+------+------+
|  22  |   2  |  3   |  23  |  4   |  34  |
|  24  |  23  |  34  |  54  |  21  |  44  |
+------+------+------+------+------+------+

+------+------+------+------+------+------+
| id_u | op_1 | op_2 | op_3 | op_4 | op_6 |
+------+------+------+------+------+------+
| min  |   2  |  3   |  23  |  4   |  34  |
| max  |  23  |  34  |  54  |  21  |  44  |
+------+------+------+------+------+------+

感谢您的帮助.. 此资源用于最近的工作http://sqlfiddle.com/#!9/297674/1

1 个答案:

答案 0 :(得分:0)

以下问题的哪个部分无法解决?

href="/page2.php?how=GO-ONE-test-24-title-stay"