1
我創建了一個數據透視表從dt_table與dt_k如何顯示動態數據透視表的最小和最大價值
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
你對這個結果做了什麼? – Strawberry
感謝您的回覆,我想用最大值或最小值來計算每行的距離 – topimiring
而您只是想在命令行上顯示此值? – Strawberry