我想从我的桌子上得到一个特殊的结果,我想知道这是可能的!? 我有这样一个表:(idA,idB,val)这个值:
idA | idB | val ----+-------+---------- 1 | 5 | 50 1 | 6 | 0 1 | 7 | NULL 2 | 5 | 100 2 | 6 | 12 2 | 7 | 0
我希望通过以下格式从此表中选择:
idA | 5 | 6 | 7 ----+-------+-------+------- 1 | 50 | 0 | NULL 2 | 100 | 12 | 0
怎么可能?
注意:我有一些搜索但什么都没找到,如果你知道一个好的关键词对我有用。
答案 0 :(得分:4)
您可以尝试此查询:
SELECT idA
,GROUP_CONCAT(CASE WHEN idB = 5 THEN val ELSE NULL END) AS `5`
,GROUP_CONCAT(CASE WHEN idB = 6 THEN val ELSE NULL END) AS `6`
,GROUP_CONCAT(CASE WHEN idB = 7 THEN val ELSE NULL END) AS `7`
FROM MyTable
GROUP BY idA
如果您不知道idB
的数量,可以使用此动态查询:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'GROUP_CONCAT(CASE WHEN `idB` = ''',
`idB`,
''' THEN val ELSE NULL END) AS `',
`idB`, '`'
)
) INTO @sql
FROM MyTable;
SET @sql = CONCAT('SELECT idA, ', @sql,'
FROM MyTable
GROUP BY idA
');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
输出:
| IDA | 5 | 6 | 7 |
---------------------------
| 1 | 50 | 0 | (null) |
| 2 | 100 | 12 | 0 |
答案 1 :(得分:1)
你可以试试这个
select idA ,
max(CASE WHEN idB = 5 then val end) as '5',
max(CASE WHEN idB = 6 then val end) as '6',
max(CASE WHEN idB = 7 then val end) as '7'
from Table1
GROUP BY idA
输出:
| IDA | 5 | 6 | 7 |
---------------------------
| 1 | 50 | 0 | (null) |
| 2 | 100 | 12 | 0 |