我有数据。
A, STATUS, P
A1, 1, P1
A1, 1, P2
A1, 1, P3
A2, 1, P3
A2, 1, P4
A2, 1, P5
A3, 0, NULL
我想要结果相同
P, A1, A2, A3
P1, 1, 0, 0
P2, 1, 0, 0
P3, 1, 1, 0
P4, 0, 1, 0
P5, 0, 1, 0
我怎么能用mysql查询呢?
答案 0 :(得分:3)
试试这个;)
select
`P`,
max(if(`A` = 'A1', `STATUS`, 0)) as `A1`,
max(if(`A` = 'A2', `STATUS`, 0)) as `A2`,
max(if(`A` = 'A3', `STATUS`, 0)) as `A3`
from table1
where `P` IS NOT NULL
group by `P`
<强>编辑:强>
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(`A` = ''',
`A`,
''', `STATUS`, 0)) AS ',
`A`
)
) INTO @sql
FROM table1;
SET @sql = CONCAT('SELECT `P`, ', @sql, ' FROM table1 WHERE `P` IS NOT NULL GROUP BY `P`');
PREPARE stmt FROM @sql;
EXECUTE stmt;
<强> DEMO HERE 强>
答案 1 :(得分:2)
假设您知道潜在列的最大数量,则可以使用conditional aggregation
来转移结果:
select p,
max(case when a = 'A1' then status else 0 end) a1,
max(case when a = 'A2' then status else 0 end) a2,
max(case when a = 'A3' then status else 0 end) a3
from yourtable
group by p
如果您不知道潜在列的数量,则需要使用dynamic sql
代替。