MSSQL,为每列B列获取A列中的最大值

时间:2013-10-15 05:48:14

标签: sql sql-server

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   | 

该表显示了一个人在十年内撰写的文章数量。例如,Bel在1930年写了6篇文章,1980年10篇,1990年2篇。

我需要每隔几十年才能找到撰写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

我被困住了。所以我的问题是,我是如何得到每十年撰写大部分文章的作者?

3 个答案:

答案 0 :(得分: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小提琴示例)

答案 1 :(得分: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

答案 2 :(得分: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

小提琴here

它们都会导致:

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