sql查找具有不同列值的行

时间:2016-02-14 12:28:53

标签: mysql sql-server

我的数据库表是(它有数百万条记录)

ol li:before { content: counters(item, ".") " "; counter-increment: item; font-weight:bold; }

我想找到排名发生变化的网站。 在上面的插图雅虎和AOL已经改变。我尝试了几个查询,但无法让它工作。

5 个答案:

答案 0 :(得分:2)

它是一个简单的选择,分组和查询,如下所示:

SELECT sitename,MAX(rank) - MIN(rank) as changed
FROM YourTable
GROUP BY sitename
HAVING COUNT(DISTINCT rank) > 1

答案 1 :(得分:1)

根据给出的想法,这就是我所拥有的:

SELECT sitename, rank, rank - (SELECT rank from sites WHERE sitename = main.sitename ORDER BY date LIMIT 1,2) as rankChange
FROM sites as main
WHERE date <= NOW()
GROUP BY sitename
HAVING COUNT(DISTINCT rank) > 1

这将返回

sitename    rank    rankChange
aol.com        4             1
yahoo.com      3            -1

如果从查询中删除HAVING COUNT(DISTINCT rank) > 1,您将看到具有未更改的网站的集合:

sitename    rank    rankChange
aol.com        4             1
facebook.com   1             0
gmail.com      2             0
yahoo.com      3            -1

答案 2 :(得分:0)

试试这个:

Select sitename from table group by sitename having count(*) > 1 order by sitename, rank DESC

答案 3 :(得分:0)

你可以这样做:

select * from your_table t_outer
group by sitename, date
having rank <> (select rank from your_table t_internal 
where t_outer.date > t_internal.date and t_outer.sitename = t_internal.sitename
order by t_internal.date limit 1)

并输出:

enter image description here

答案 4 :(得分:0)

如下所示。而且您每天都需要为每个站点创建记录

SELECT sitename, MAX(rank) - MIN(rank) as ChangeRank
FROM ChangeHistoryTable
WHERE date between dateFromWhichYouNeedChanges and dateToWhichYouNeedChanges
GROUP BY sitename
HAVING COUNT(DISTINCT rank) > 1