我有一张类似的表:
customer employee
------ ---------
A Adam
A Adam
A Adam
B Bob
C Adam
C Adam
B Bob
D Dan
我试图弄清楚如何显示亚当有多少次重复客户以及鲍勃有多少次。 所以在上面的例子中它会返回:
Adam => 2(他有2个回头客,客户A和C)
Bob => 1(他有1个重复客户,客户b)
Dan => 0(他只有一个顾客,没有重复)
到目前为止我所拥有的是:
SELECT customer, COUNT(*) as cnt
FROM table
GROUP BY employee
HAVING cnt > 1
但我似乎无法完成剩下的工作。
答案 0 :(得分:3)
您可以尝试以下查询:
SELECT
t.employee, COUNT(*) AS cnt
FROM
(SELECT
employee, customer, COUNT(*) AS actcnt
FROM
customers
GROUP BY customer , employee HAVING actcnt > 1) AS t
GROUP BY t.employee
ORDER BY t.employee;
答案 1 :(得分:2)
首先需要找到重复客户:
SELECT employee,customer FROM yourtable GROUP BY employee, customer having COUNT(*) > 1;
之后,您可以找到每个员工有多少回头客:
SELECT employee, COUNT(*) from (
SELECT employee,customer
FROM yourtable
GROUP BY employee, customer
HAVING COUNT(*) > 1
) t
GROUP BY employee;
答案 2 :(得分:0)
select employee, count(*)-1 as cnt
from t1
group by employee,customer
having cnt > 0;
答案 3 :(得分:0)
如果你COUNT重复员工:
SELECT id,customer,employee,COUNT(*) FROM USER GROUP BY employee HAVING COUNT(*)>0
如果你COUNT重复客户:
SELECT id,customer,employee,COUNT(*) FROM USER GROUP BY customer HAVING COUNT(*)>0
//注意:我总计数,你改了)COUNT()> 0到COUNT()> 1 &安培;&安培;表=用户为
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`customer` varchar(200) DEFAULT NULL,
`employee` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
/ *表user
* /
insert into `user`(`id`,`customer`,`employee`)
values (1,'A','Adam'),(2,'A','Adam'),(3,'A','Adam'),(4,'B','Bob'),(5,'C','Adam'),(6,'C','Adam'),(7,'B','Bob'),(8,'D','Dan');
答案 4 :(得分:-1)
选择客户,员工 从表 GROUP BY客户,员工 有计数(*)> 1