2013-10-15 58 views
1
id name NumofPup  Decade 
---|-----|------------|--------| 
1 | Ace | 7   | 1930 | 
2 | Bel | 6   | 1930 | 
3 | Cha | 2   | 1930 | 
4 | Bel | 10   | 1980 | 
5 | Dew | 6   | 1980 | 
6 | Bel | 2   | 1990 | 

下表显示了一个人在十年中写了多少篇文章。例如,贝尔在1930年写了6篇文章,1980年写了10篇,1990年2篇。MSSQL,获得列A中每列B列的最大值

我每隔几十年就需要一次,得到写MOST文章的人。结果应该是这样的:

id name NumofPup  Decade 
---|-----|------------|--------| 
1 | Ace | 7   | 1930 | 
4 | Bel | 10   | 1980 | 
6 | Bel | 2   | 1990 | 

下面的代码是我到目前为止,生成表1:

SELECT authDec.name, COUNT(authDec.name) as NumOfPupPerDECADE, authDec.decade 
FROM 
    (
    SELECT a.name, year, (year/10)*10 AS decade 
    FROM publication pub, author a, authored auth 
    WHERE year IS NOT NULL and pub.pubId = auth.pubId and auth.id = a.id 
) as authDec 
GROUP BY authDec.name, authDec.decade 
ORDER BY authDec.decade, NumOfPupPerDECADE DESC 

笔者认为名称和的AuthorID 公布持有的pubId和ArticleName的 著作持有的AuthorID和PubID的

而我被卡住了。所以我的问题是,我如何获得每十年编写大多数文章的作者?

回答

1

一个这样做的方法是使用ROW_NUMBER()函数:

with cte as (
    select *, row_number() over(partition by Decade order by NumofPup desc) as rn 
    from Table1 
) 
select id, name, NumofPup, Decade 
from cte 
where rn = 1 

或者这样:

select t.id, t.name, t.NumofPup, t.Decade 
from Table1 as t 
where 
    exists (
     select 1 
     from Table1 as t2 
     where t2.Decade = t.Decade 
     having max(t2.NumofPup) = t.NumofPup 
    ) 

sql fiddle demo

注意,这儿有威力不止一个人写了十年以来最多的文章,所以冷杉牛逼的查询将返回第一人,是谁写的最多,第二次查询将返回所有的人(请参阅SQL小提琴例子)

0

试试这个字母顺序:

DECLARE @TABLE TABLE (ID INT, NAME VARCHAR(40), NUMOFPUP INT, DECADE INT) 
INSERT INTO @TABLE VALUES 

(1 , 'ACE' , 7   , 1930) , 
(2 , 'BEL' , 6   , 1930) , 
(3 , 'CHA' , 2   , 1930) , 
(4 , 'BEL' , 10   , 1980) , 
(5 , 'DEW' , 6   , 1980) , 
(6 , 'BEL' , 2   , 1990) 

SELECT 
    ID, 
    NAME, 
    NUMOFPUP, 
    DECADE 
FROM 
    @TABLE A 
WHERE 
    A.NUMOFPUP = (SELECT MAX(NUMOFPUP) FROM @TABLE B WHERE A.DECADE = B.DECADE GROUP BY B.DECADE) 
ORDER BY 
    A.DECADE ASC 
0

通常有2种解决这些问题,那会的方式在任何DBMS的工作:

LEFT JOIN方法:

SELECT t1.* FROM t t1 
LEFT JOIN t t2 ON t1.Decade = t2.Decade AND t1.NumOfPup < t2.NumOfPup 
WHERE t2.Decade IS NULL; 

子查询方法:

SELECT t1.* FROM t t1 
INNER JOIN (
    SELECT Decade, max(NumOfPup) maxNumOfPup FROM t 
    GROUP BY Decade 
) s ON t1.Decade = s.Decade AND t1.NumOfPup = s.maxNumOfPup 

小提琴here

他们都将导致:

| ID | NAME | NUMOFPUP | DECADE | 
|----|------|----------|--------| 
| 1 | Ace |  7 | 1930 | 
| 4 | Bel |  10 | 1980 | 
| 6 | Bel |  2 | 1990 | 
相关问题