使用where子句选择2个字段的计数大于1的行

时间:2012-03-19 10:23:35

标签: mysql

我有一个看起来像这样的表:

╔════╦═════════╦═════════╦═══════╗  
║ id ║ deleted ║ status  ║  ref  ║  
╠════╬═════════╬═════════╬═══════╣  
║  1 ║       0 ║ pending ║ 10001 ║  
║  2 ║       0 ║ paid    ║ 10001 ║  
║  3 ║       0 ║ paid    ║ 10001 ║  
║  4 ║       0 ║ paid    ║ 10002 ║  
║  5 ║       1 ║ pending ║ 10002 ║  
║  6 ║       1 ║ paid    ║ 10002 ║  
║  7 ║       0 ║ pending ║ 10003 ║  
║  8 ║       0 ║ paid    ║ 10003 ║  
║  9 ║       0 ║ paid    ║ 10003 ║  
║ 10 ║       0 ║ paid    ║ 10003 ║  
║ 11 ║       0 ║ pending ║ 10004 ║  
║ 12 ║       0 ║ paid    ║ 10004 ║  
║ 13 ║       1 ║ pending ║ 10005 ║  
║ 14 ║       1 ║ paid    ║ 10005 ║  
║ 15 ║       1 ║ paid    ║ 10005 ║  
║ 16 ║       0 ║ paid    ║ 10005 ║  
║ 17 ║       0 ║ pending ║ 10006 ║  
║ 18 ║       0 ║ paid    ║ 10006 ║  
║ 19 ║       0 ║ paid    ║ 10006 ║  
╚════╩═════════╩═════════╩═══════╝

我正在尝试编写一个MySQL查询,该查询将返回paid而不是deleted的行。 但仅限于paid的计数大于1的情况。所以结果应为:

╔════╦═════════╦════════╦═══════╗
║ id ║ deleted ║ status ║  ref  ║
╠════╬═════════╬════════╬═══════╣
║  2 ║       0 ║ paid   ║ 10001 ║
║  3 ║       0 ║ paid   ║ 10001 ║
║  8 ║       0 ║ paid   ║ 10003 ║
║  9 ║       0 ║ paid   ║ 10003 ║
║ 10 ║       0 ║ paid   ║ 10003 ║
║ 18 ║       0 ║ paid   ║ 10006 ║
║ 19 ║       0 ║ paid   ║ 10006 ║
╚════╩═════════╩════════╩═══════╝

我一直在尝试使用以下查询来获取此信息,但它并不能满足我的需要而且我现在似乎正在转圈。有人可以帮我一把吗?

SELECT t1.* FROM orders t1 WHERE exists (SELECT * FROM orders t2 where t1.id != t2.id and t1.ref = t2.ref and t1.deleted = 0 and t1.status = 'paid')

非常感谢!

[编辑] arrgh!对不起,我忘了说我只需要返回超过1 paid状态的行...抱歉......

3 个答案:

答案 0 :(得分:2)

请使用以下内容(不要有数据库实例):

SELECT t.*
FROM orders t
INNER JOIN
(
    SELECT ref, deleted, status
    FROM orders
    WHERE deleted = 0 and status = 'paid'
    GROUP BY ref
    HAVING count(ref) > 1
) d
ON t.ref = d.ref
AND t.status = d.status
AND t.deleted = d.deleted;

(基于http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=68374

答案 1 :(得分:1)

给这个打击:

select o.*
from orders o
inner join
(
 select ref, 
 sum(case when status = 'paid' then 1 else 0 end) as paid_count,
 count(distinct status) as total_distinct_status_count
 from orders yt
 where deleted = 0
 group by ref
) t1 on t1.ref = o.ref
where o.status = 'paid'
and o.deleted = 0
and t1.paid_count > 1
and t1.total_distinct_status_count > 1;

似乎给出了已发布数据的答案。

答案 2 :(得分:-1)

我认为你正在努力解决这个问题...... 休息一下,再次启动你的代码。 无论如何答案已经在第一个回答中给出了...... Chilllllll