我正在努力获得正确的数据返回,我有一个包含以下数据结构的表:
# order_id, name
'10434', 'docs_sent'
'10433', 'placed'
'10433', 'docs_sent'
'10433', 'agreement_received'
'10432', 'placed'
'10431', 'placed'
'10431', 'docs_sent'
'10430', 'placed'
'10430', 'docs_sent'
'10430', 'agreement_received'
'10429', 'placed'
'10429', 'docs_sent'
'10429', 'agreement_received'
'10428', 'placed'
'10428', 'docs_sent'
'10427', 'placed'
我要做的是返回一个独特的" order_id"在哪里"名称"不包括agreement_received。所以澄清我正在寻找一个订单号列表" order_id"其中订单号与agreement_received"没有任何记录。问题是每个订单都有多个条目,我似乎无法做到正确。请帮助!
输出应类似于:
# order_id
'10434'
'10432'
'10431'
'10428'
'10427'
答案 0 :(得分:1)
您希望按 order_id分组,并且只保留那些没有' agreement_received'记录。
select order_id
from mytable
group by order_id
having sum(name = 'agreement_received') = 0;
(这使用MySQL的特殊布尔处理.False = 0,True = 1.在其他dbms中你必须使用sum(case when name = 'agreement_received' then 1 else 0 end)
。)
答案 1 :(得分:0)
select distinct order_id
from orders
where name != 'agreement_received';
这对你有用吗?
答案 2 :(得分:0)
尝试类似:
SELECT order_id
FROM MyTable
WHERE name <> 'agreement_received'
GROUP BY order_id
HAVING COUNT(order_id) = 1
答案 3 :(得分:0)
如果您的表名是t
:
select distinct t1.order_id
from t as t1
where t1.order_id not in
(select t2.order_id
from t as t2
where t2.name = 'agreement_received')
输出:
+----------+
| order_id |
+----------+
| 10434 |
| 10432 |
| 10431 |
| 10428 |
| 10427 |
+----------+