我是mysql的新手,我有这样的结构
timestamp | Name | Total | Student1 | Student2 | Student3
20150911 | X | 100 | 76 | 10 | NA
20151111 | Y | 70 | NA | 0 | 23
现在我想在给定'timestamp'
的情况下选择mysql查询预期结果
我一直试图寻找这样的混合选择,但到目前为止我还没有成功。大多数答案都集中在行选择而不是列。
答案 0 :(得分:2)
您的数据结构未规范化。但如果你想走这条路,请使用:
select sub.student
FROM (
select t.timestamp,
t.Name,
t.Total,
c.col AS student,
case c.col
when 'Student1' then Student1
when 'Student2' then Student2
when 'Student3' then Student3
-- ...
end as d
from mytable t
cross join
(
select 'Student1' as col
union all select 'Student2'
union all select 'Student3'
-- ...
) c
) AS sub
WHERE sub.timestamp = '20150911'
AND sub.d > 0;
-- sub.d = 'NA'
-- sub.d = 0
的 SqlFiddleDemo
强>
输出:
╔══════════╗
║ student ║
╠══════════╣
║ Student1 ║
║ Student2 ║
╚══════════╝
如果您想使用逗号分隔结果:
select GROUP_CONCAT(sub.student ORDER BY sub.student) AS result
的 SqlFiddleDemo2
强>
输出:
╔═══════════════════╗
║ result ║
╠═══════════════════╣
║ Student1,Student2 ║
╚═══════════════════╝