查询以获取最终状态为失败或在任何一个列出的主题在配置单元中失败或不存在时缺席

时间:2016-05-16 06:31:32

标签: mysql database hive db2

 select * from college;
    btech   cse     dbms    fail
    btech   cse     java    absent
    btech   cse     unix    pass
    btech   ece     edc     pass
    btech   ece     power   pass
    btech   ece     embeded pass
    mba     marketing       mlaw    pass
    mba     marketing       mtheory fail
    mba     hr      hrtheory1        pass
    mba     hr      hrtheory2        absent

输出应该是这样的: -

btech cse fail
btech ece pass
mba  marketing fail
mba hr hrtheory absent

2 个答案:

答案 0 :(得分:1)

我假设您的上一个结果是mba hr absent,我为您的列添加了一些名称。试试以下,可能会对你有帮助;)

SQL Fiddle

MySQL 5.6架构

CREATE TABLE college
    (`name` varchar(5), `major` varchar(9), `class` varchar(9), `result` varchar(6))
;

INSERT INTO college
    (`name`, `major`, `class`, `result`)
VALUES
    ('btech', 'cse', 'dbms', 'fail'),
    ('btech', 'cse', 'java', 'absent'),
    ('btech', 'cse', 'unix', 'pass'),
    ('btech', 'ece', 'edc', 'pass'),
    ('btech', 'ece', 'power', 'pass'),
    ('btech', 'ece', 'embeded', 'pass'),
    ('mba', 'marketing', 'mlaw', 'pass'),
    ('mba', 'marketing', 'mtheory', 'fail'),
    ('mba', 'hr', 'hrtheory1', 'pass'),
    ('mba', 'hr', 'hrtheory2', 'absent')
;

查询1

select
 name, major,
 case 
 when find_in_set('fail', group_concat(result)) > 0 then 'fail'
 when find_in_set('fail', group_concat(result)) = 0
      and find_in_set('absent', group_concat(result)) = 0
      and find_in_set('pass', group_concat(result)) > 0 then 'pass'
 when find_in_set('fail', group_concat(result)) = 0
      and find_in_set('absent', group_concat(result)) > 0
      and find_in_set('pass', group_concat(result)) > 0 then 'absent' end as result
from college
group by name, major

<强> Results

|  name |     major | result |
|-------|-----------|--------|
| btech |       cse |   fail |
| btech |       ece |   pass |
|   mba |        hr | absent |
|   mba | marketing |   fail |

在Hive中,可能会喜欢这个;)

select
 name, major,
 case 
 when ARRAY_CONTAINS('fail', collect_set(result)) then 'fail'
 when ARRAY_CONTAINS('fail', collect_set(result))
      and ARRAY_CONTAINS('absent', collect_set(result))
      and ARRAY_CONTAINS('pass', collect_set(result)) then 'pass'
 when ARRAY_CONTAINS('fail', collect_set(result))
      and ARRAY_CONTAINS('absent', collect_set(result))
      and ARRAY_CONTAINS('pass', collect_set(result)) then 'absent' end as result
from college
group by name, major

答案 1 :(得分:0)

我不确定你对最终状态的意思,但是你可以得到你用这个查询描述的输出:

SELECT * FROM college WHERE col4 = 'fail' OR col4 = 'absent';

如果您没有比“失败”更多的变量,“缺席”,“通过&#39;”,您可以使用

SELECT * FROM college WHERE col4 <> 'pass';