MYSQL行转列例子

SELECT
person_id id,
max( CASE sex WHEN ‘男’ THEN ff.NAME END ) name1,
max( CASE sex WHEN ‘男’ THEN ff.sex END ) sex1,
max( CASE sex WHEN ‘女’ THEN ff.NAME END ) name2,
max( CASE sex WHEN ‘女’ THEN ff.sex END ) sex2
FROM
(
SELECT
bb.person_id,
bb.NAME,
bb.sex
FROM
B bb
JOIN (
SELECT
a.id id,
sum( 1 )
FROM
A a
JOIN B b ON a.id = b.person_id
GROUP BY
a.id
HAVING
sum( 1 ) >= 2
) tt ON bb.person_id = tt.id
) ff
GROUP BY
ff.person_id;

你可能感兴趣的:(开发笔记)