选择大于某个值的所有列

时间:2015-11-11 10:53:45

标签: mysql sql database

我是mysql的新手,我有这样的结构

timestamp | Name | Total | Student1 | Student2 | Student3
20150911  | X    | 100   |       76 |       10 |       NA
20151111  | Y    | 70    |       NA |        0 |       23

现在我想在给定'timestamp'

的情况下选择mysql查询
  • 所有具有非零数字的学生列
  • NA的所有学生专栏
  • 所有学生列为零

预期结果

  • 如果我输入'非零'查询,则应将列名称为“Student1,Student2”,时间戳为20150911
  • 如果我将'零'查询,它应该为列的名称为()为时间戳20150911
  • 如果我输入“NA”查询,则应将列名称为“Student3”,时间戳为20150911

我一直试图寻找这样的混合选择,但到目前为止我还没有成功。大多数答案都集中在行选择而不是列。

1 个答案:

答案 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 ║
╚═══════════════════╝