Mysql Group按功能

时间:2014-04-12 04:50:02

标签: mysql

这是我的表:

Id customer email        timestamp             store_id
1    1      abc@xx.com   2014-04-11 17:06:21   5416
2    0      xyz@xy.com   2014-04-11 15:05:23   5416
3    1      abc@xx.com   2014-04-11 17:55:34   5416
4    2      bca@bc.com   2014-04-11 17:55:34   5416

我的查询是:

SELECT *, count(*) as total FROM `tybo_orders` 
WHERE timestamp IN (SELECT max(timestamp) FROM `tybo_orders`
GROUP BY email) AND store_id='5416' GROUP BY email

customer列中的值0表示来宾,而大于0表示客户ID。如果email为0,则我希望按customer进行分组customer。怎么可能?

2 个答案:

答案 0 :(得分:0)

我认为这样可行:

SELECT *, count(*) as total 
FROM `tybo_orders` 
WHERE timestamp IN (SELECT max(timestamp) FROM `tybo_orders` GROUP BY email) 
AND 
store_id='5416' 
GROUP BY 
IF(customer=0,email,customer)

答案 1 :(得分:0)

尝试这样

SELECT *, count(*) as total 
FROM `tybo_orders` 
WHERE timestamp IN (SELECT max(timestamp) FROM `tybo_orders` GROUP BY email) 
AND 
store_id='5416' 
GROUP BY 
case when customer=0 then customer else email end