SQL选择与同一个表中的多个条件匹配的行

时间:2017-01-10 17:58:49

标签: sql sql-server database

我有下表:

MockRestService

我只需要提取符合此条件的行:

event_id必须仅包含某些值,例如,必须包含UYALR和PAF。

这是真正的桌子:

enter image description here

正如您所看到的,每个alarminc_no都有很多偶数,我只需要看到具有PAF或PFA作为eventID的alarminc_no,并且仅需要以下EventIDS:

+-------------+------------+----------+---------+
| alarminc_no | cust_name  | event_id | site_no |
+-------------+------------+----------+---------+
|       99999 | Jonh Smith | UYALR    |    9090 |
|       99999 | Jonh Smith | UYBR     |    9090 |
|       99999 | Jonh Smith | PAF      |         |
|       77777 | Allan      | UYBIC    |    9090 |
|       77777 | Allan      | UYBR     |    9090 |
|       77777 | Allan      | PAF      |    9090 |
|       88888 | Susan      | UYGR     |    9090 |
|       88888 | Susan      | UYLAR    |    9090 |
|       88888 | Susan      | PAF      |    9090 |
+-------------+------------+----------+---------+

所以,如果一个alarminc_no在事件ID中有PAF,但没有其他IDS,或其他不是这些,那么我不希望它在输出上。

对不起,我尽力解释这个烂摊子。

2 个答案:

答案 0 :(得分:0)

这将为拥有UYALR和PAF但不是UYLOL的用户提供alarminc_no。

select alarminc_no
from your_table
group by alarminc_no
having count (
    distinct case when
        event_id in ('UYALR','PAF')
    then event_id end
) = 2 and count (
    case when event_id = 'UYLOL' then 1 end
) = 0;

答案 1 :(得分:0)

let request = require('request');
let promise = require('promise');
let done = false;
let poll = promise.denodeify(request.get).bind(request);
let p = poll(serviceURL);
let handle = setInterval(() => {
  p.then(res => {
    if (res === endingCondition) {
      done = true;
      clearInterval(handle);
    }

    if (!done) {
      p = poll(serviceURL);
    } 
  });
}, 500);

根据评论进行更新

SELECT alarmic_no 
FROM (
  SELECT alarmic_no,
     CASE WHEN eventid in
       ('PAF','PFA','USABA','USALR','USBUR','USDUR','USFIR','USPAN','USTAM',
        'UYALR','UYAVI','UYBUR','UYDIR','UYDUR','UYE73','UYFIR','UYMED',
        'UYPAN','UYTAM') THEN 0 ELSE 1 END AS BAD,
     CASE WHEN eventid in ('PAF','PFA') THEN 1 ELSE 0 END AS GOOD
  FROM tablename
) X
GROUP BY alarmic
HAVING SUM(BAD) = 0 AND SUM(GOOD) > 0 AND COUNT(*) > 1