我有一个包含id
(int)和sell_date
(datetime)的表。这些是客户id
和销售日期。我必须得到客户的数量,他们每个月至少买2次,按DATE_FORMAT(sell_date,'%Y-%m') AS period
分组。
例如:我的客户端id = 1。他在01 - 2014年买了一次东西,在02-2014买了2次,在03-2014买了3次。所以我想得到这个:
period |repeated_buyers
2014-01 | (none)
2014-02 | 1
2014-03 | 1
我不如SQL。非常感谢你提前!
答案 0 :(得分:0)
你快到了。您需要在日期<{1}}上进行<{1}}
group by
答案 1 :(得分:0)
试试这个:
select DATE_FORMAT(sell_date,'%Y-%m') AS period,COUNT(ID) as repeated_buyers
from MyTable
GROUP BY ID,DATE_FORMAT(sell_date,'%Y-%m')
having COUNT(ID)>=2
答案 2 :(得分:0)
啊,我做到了!
SELECT `period`,
count(`id`) as `accounts`
FROM (SELECT
DATE_FORMAT(`sell_date`,'%Y-%m') AS `period`,
`id` FROM `terst` GROUP BY `period`, `id` HAVING COUNT(`id`)>1 )A
GROUP BY `period`
答案 3 :(得分:0)
尝试下面的sql查询,
select id,period,repeated_buyers from(select DATE_FORMAT(sell_date,'%Y-%m') AS period,id,
Count(*) as repeated_buyers
from TABLE1
group by DATE_FORMAT(sell_date,'%Y-%m'),id) where repeated_buyers>=2;