0

我需要帮助编写 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')

我想从上表中查询 where 并获得不同的 mobileno1234,2345,4326,4327及其状态,例如该 mobileno 是否成功,它应该返回带有 id 和状态的记录,如果任何移动()都没有成功,in my case it is 4326那么这也应该在执行的查询中可见。

例如,我想要这样的东西:

+---+  +--------+  +----------+
|id |  |mobileno|  |  status  |
+---+  +--------+  +----------+
|3  |  |  1234  |  |  success |
|5  |  |  2345  |  |  success |
|6  |  |  4326  |  |  fail    |
|7  |  |  4327  |  |  success |
+---+  +--------+  +----------+
4

2 回答 2

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

http://sqlfiddle.com/#!2/e71e7/3

于 2013-06-18T10:59:01.957 回答
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
于 2013-06-18T11:03:02.070 回答