我有一张这样的表:
Name CPP Java Python Age
David 1 1 0 40
Mike 1 0 1 50
我想为每个非零CPP / Java / Python值生成一行,并清除其他非零值:
Name CPP Java Python Age
David 1 0 0 40
David 0 1 0 40
Mike 1 0 0 50
Mike 0 0 1 50
我该怎么做?
答案 0 :(得分:2)
这应该是魔术:
SELECT name, cpp, 0,0, Age FROM table WHERE cpp = 1 UNION ALL
SELECT name, 0, Java,0, Age FROM table WHERE Java = 1 UNION ALL
SELECT name, 0, 0,Python, Age FROM table WHERE Python = 1
答案 1 :(得分:1)
简单的方法是建立联盟,例如,
SELECT name, cpp, 0 as java, 0 as python, age
FROM {table}
WHERE cpp = 1
UNION ALL
SELECT name, 0 as cpp, java, 0 as python, age
FROM {table}
WHERE java = 1
UNION ALL
SELECT name, 0 as cpp, 0 as java, python, age
FROM {table}
WHERE python = 1
答案 2 :(得分:1)
我想你想做的是这样的事情:
SELECT t.Name,t.CPP,t.Java,t.Python,t.Age FROM(
SELECT Name, CPP, 0 AS Java, 0 AS Python, Age Where CPP = 1
UNION
SELECT Name, 0 AS CPP, Java, 0 AS Python, Age Where Java = 1
UNION
SELECT Name, 0 AS CPP, 0 AS Java, Python, Age Where Python = 1 ) t
ORDER BY t.Name ASC;
希望这有帮助。