我需要帮助编写sql查询以根据状态查找记录。我使用此查询创建了一个表:
CREATE TABLE inglogs (id int, mobileno int(10), status varchar(10));
INSERT INTO inglogs (id, mobileno, status)
VALUES
(1, 1234, 'fail'),
(2, 1234, 'fail'),
(3, 1234, 'success'),
(4, 2345, 'success'),
(5, 2345, 'success'),
(6, 4326, 'fail'),
(7, 4327, 'success')
我想从上面的表中查询并获取与1234,2345,4326,4327
不同的mobileno,其状态如果该mobileno有任何成功,它应该返回具有id和status的记录,如果没有任何移动设备(in my case it is 4326
)的任何成功都应该在执行的查询中可见。
例如我想要这样的事情:
+---+ +--------+ +----------+
|id | |mobileno| | status |
+---+ +--------+ +----------+
|3 | | 1234 | | success |
|5 | | 2345 | | success |
|6 | | 4326 | | fail |
|7 | | 4327 | | success |
+---+ +--------+ +----------+
请帮帮我。
答案 0 :(得分:2)
您想要一个带条件的聚合:
select max(id) as id, mobileno,
(case when sum(status = 'success') > 0 then 'success' else 'fail' end) as status
from inglogs
group by mobileno
见sqlfiddle
答案 1 :(得分:0)
您可以粗略地执行此操作: -
SELECT MAX(id), mobileno, MAX(status)
FROM inglogs
GROUP BY mobileno
虽然这依赖于成功大于失败(即,如果你的状态为“未知”,那么它也会失败)
或使用子选择: -
SELECT MAX(id), mobileno, CASE WHEN sub1.mobileno IS NULL THEN 'fail' ELSE 'success' END AS status
FROM inglogs a
LEFT OUTER JOIN (SELECT mobileno, COUNT(*) FROM inglogs WHERE status = 'success' GROUP BY mobileno) sub1
ON a.mobileno = sub1.mobileno
GROUP BY mobileno