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 篇。

我需要每隔几十年,找到写最多文章的人。结果应该是这样的:

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

Author 保存姓名和 AuthorID Publication 保存 pubID 和 ArticleName Authored 保存 AUthorID 和 pubID

我被困住了。所以我的问题是,我如何获得每十年撰写最多文章的作者?

4

3 回答 3

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 fiddle 示例)

于 2013-10-15T05:52:35.497 回答
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
于 2013-10-15T06:24:10.673 回答
0

通常有两种方法可以在任何 DBMS 中解决这些问题:

左连接方法:

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

在这里拉小提琴。

它们都将导致:

| ID | NAME | NUMOFPUP | DECADE |
|----|------|----------|--------|
|  1 |  Ace |        7 |   1930 |
|  4 |  Bel |       10 |   1980 |
|  6 |  Bel |        2 |   1990 |
于 2013-10-15T06:53:52.613 回答