2014-11-24 117 views
0

我有一個在線商店,與訂單DB是這樣的:高級MySQL分組查詢

id purchase_date buyer_name buyer_email product_name delivery_status 
1 10.09.2014  jo smith [email protected] dildo   delivered 
2 10.09.2014  jo smith [email protected] superdildo delivered 
3 11.09.2014  john lol [email protected] cream   delivered 
4 13.09.2014  john lol [email protected] supercream not delivered 
5 15.09.2014  john doe [email protected] lingerie  delivered 
6 15.09.2014  john doe [email protected] lingerie2  not delivered 
7 15.09.2014  feels no [email protected] supercream delivered 
8 18.09.2014  jo smith [email protected] cream   not delivered 

我要選擇從該表中,其中 所有在該日的客戶訂單都是不同的BUYER_EMAIL的「交付」。

我的意思是:

ID 1和2是一根火柴,查詢應輸出[email protected],因爲這兩個訂單他沒有在那一天交付。

ID 3也是一個匹配項,導致當天(2014年9月11日)投遞的所有訂單都是[email protected]

ID 4不會在查詢(未在該名稱當天的所有命令被送到)

ID 5和6不會被任一匹配相匹配。

ID 7是匹配

ID 8不匹配。

回答

1

您想要使用having子句進行聚合。至少要開始。下面得到天,購房者已經完全交付訂單:

select o.purchase_date, o.buyer_email 
from orders o 
group by o.purchase_date, o.buyer_email 
having sum(delivery_status <> 'delivered') = 0; 

如果你想在訂單ID,最簡單的方法是使用group_concat()

select o.purchase_date, o.buyer_email, group_concat(o.id) as ids 
from orders o 
group by o.purchase_date, o.buyer_email 
having sum(delivery_status <> 'delivered') = 0; 

如果你想整行,你可以使用join

2
select distinct buyer_email 
from your_table 
group by buyer_email, purchase_date 
having sum(delivery_status <> 'delivered') = 0