如何获得每个用户贡献/出现在该特定类别的数量。下表有用户,类别。我正在寻找所有用户已经贡献/出现在下表中并对其进行排名的锄头计数。
http://sqlfiddle.com/#!2/d4458/2
CREATE TABLE if not exists tblA
(
id int(11) NOT NULL auto_increment ,
user varchar(255),
category int(255),
PRIMARY KEY (id)
);
INSERT INTO tblA (user, category ) VALUES
('1', '1'),
('1', '2'),
('1', '3'),
('1', '1'),
('2', '1'),
('2', '1');
响应如下:搜索其' 1'
的类别user category count rank
1 1 2 1
2 1 2 2
答案 0 :(得分:2)
SELECT USER,
category,
count(*) AS num
FROM tblA
WHERE category=1
GROUP BY USER,
category
ORDER BY num DESC;
答案 1 :(得分:1)
SET @prev_value = NULL;
SET @rank_count = 0;
SELECT
i.*,
CASE
WHEN @prev_value = i.num THEN @rank_count
ELSE @rank_count := @rank_count + 1
END AS rank
FROM (
SELECT
user,category,COUNT(*) AS num
FROM tblA
WHERE category=1
GROUP BY user,category
ORDER BY num DESC
) i;