这是我的 SQL 小提琴:http ://sqlfiddle.com/#!2/90d45/3
表方案:
CREATE TABLE domain_rankings (domain_id int, rank int, create_date datetime);
INSERT INTO domain_rankings VALUES (1, 0, "2012-01-01");
INSERT INTO domain_rankings VALUES (1, 2, "2012-01-02");
INSERT INTO domain_rankings VALUES (1, 1, "2012-01-03");
INSERT INTO domain_rankings VALUES (2, 0, "2012-01-01");
INSERT INTO domain_rankings VALUES (2, 1, "2012-01-02");
INSERT INTO domain_rankings VALUES (2, 2, "2012-01-03");
INSERT INTO domain_rankings VALUES (3, 1, "2012-01-01");
INSERT INTO domain_rankings VALUES (4, 3, "2012-01-01");
INSERT INTO domain_rankings VALUES (4, 2, "2012-01-02");
INSERT INTO domain_rankings VALUES (4, 1, "2012-01-03");
我想获得比较第一个条目和最后一个条目(按日期)排名上升的 domain_id 的计数。
所以在这种情况下,所有排名上升的计数应该是 2 (domain_id: 1, 2)。
domain_id 3 不应包含在计数中,因为它只有一个条目。因此,可能需要 HAVING COUNT(*) > 1 的子查询。
domain_id 4 也不应该包含在计数中,除非我反转查询并希望排名下降。
我应该如何解决这个问题?我知道我需要子查询,但我不知道从哪里开始。JSFiddle 应该让您了解我被困在哪里。
尝试 - 这将返回有效的行,但不正确地返回行的 COUNT:
SELECT domain_id, COUNT(DR.domain_id)
FROM domain_rankings DR
WHERE
(SELECT rank
FROM domain_rankings
WHERE domain_rankings.domain_id = DR.domain_id
ORDER BY create_date ASC LIMIT 1
) > (
SELECT rank
FROM domain_rankings
WHERE domain_rankings.domain_id = DR.domain_id
ORDER BY create_date DESC LIMIT 1
)
GROUP BY DR.domain_id
HAVING count(*) > 1
最终答案(两个选项中较慢的一个):
SELECT COUNT(a.domain_id) cnt
FROM (
SELECT domain_id,MIN(create_date) mind, MAX(create_date) maxd
FROM domain_rankings
GROUP BY domain_id
HAVING COUNT(*) > 1
) master
JOIN domain_rankings a
ON a.domain_id = master.domain_id
AND a.create_date = master.mind
JOIN domain_rankings b
ON b.domain_id = master.domain_id
AND b.create_date = master.maxd
WHERE a.rank < b.rank