如何将(未分组的)列添加到分组表中?

时间:2018-09-21 16:36:29

标签: sql sql-server group-by

我是SQL编程的新手,需要解决此小问题。

锻炼:

针对每个国家/地区,找到发行最大船舶数量的年份。如果是一年以上的问题,请花最少的时间。

我有两个表,这些表通过外键“类”链接(请参见下文):

课程

enter image description here

船舶

enter image description here

我需要的是以下结果:

(maxNumber =计算每个国家/地区的年限(列:“启动”))

enter image description here

我有以下查询,几乎可以给出正确的结果:

SELECT e.country, MAX(e.number) as maxNumber
FROM(
    SELECT d.country, d.Year, count(*) as number
    FROM(
        SELECT a.country, b.launched AS Year
        FROM Classes a 
        INNER JOIN ships b ON a.class=b.class
        ) d
GROUP BY d.country, d.Year) e
GROUP BY e.country

结果:

enter image description here

我的问题:如何在表中获取“ YEAR”列而不将其添加到GROUP函数中?如果我只是在GROUP函数中添加“ year”,则Maxnumber将以Years为单位。我所需要做的就是将相关年份添加到表的每一行中(如所需结果所示)。

我希望您的SQL向导可以帮助我解决这个问题。

谢谢。 溴 雅各布

1 个答案:

答案 0 :(得分:0)

这部分有点多余:

SELECT d.country, d.Year, count(*) as number
FROM(
     SELECT a.country, b.launched AS Year
     FROM Classes a 
     INNER JOIN ships b ON a.class=b.class
     ) d
GROUP BY d.country, d.Year

您可以这样做:

SELECT a.country, b.launched AS Year, count(*) as Number
FROM Classes a 
INNER JOIN ships b ON a.class=b.class
GROUP BY a.country, b.launched

然后,您可以使用ROW_NUMBER为每个国家/地区中计数最高的行分配一个1

SELECT a.country, b.launched AS Year, count(*) as Number,
       ROW_NUMBER() over (PARTITION BY a.country ORDER BY COUNT(*) DESC) as RN
FROM Classes a 
INNER JOIN ships b ON a.class=b.class
GROUP BY a.country, b.launched

然后只需执行外部选择即可获得RN = 1所在的行:

SELECT country, year, number
FROM (SELECT a.country, b.launched AS Year, count(*) as Number,
             ROW_NUMBER() over (PARTITION BY a.country ORDER BY COUNT(*) DESC) as RN
      FROM Classes a 
      INNER JOIN ships b ON a.class=b.class
      GROUP BY a.country, b.launched
     ) A
WHERE RN = 1