[英]how do I add a (not grouped) column to a grouped table?
I am a novice in SQL programming, who needs to solve this little exercise. 我是SQL编程的新手,需要解决此小问题。
Exercise: 行使:
For each country, find the year, in which the maximal number of ships had been launched. 对于每个国家/地区,请找出发行最大船舶数量的年份。 In the case of more than one year in question, take a minimal year.
如果问题一年以上,请花最少的时间。
I have two tables, which are linked by the foreign key "class" (please see below): 我有两个表,这些表通过外键“类”链接(请参见下文):
CLASSES 类
SHIPS 船舶
What I need is the following result: 我需要的是以下结果:
(maxNumber=count the number of years (column:"launched") for each country) (maxNumber =计算每个国家/地区的年限(列:“启动”))
I have the following query which gives me - almost - the correct result: 我有以下查询,几乎可以给我正确的结果:
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
RESULT: 结果:
My problem: How do I get the column "YEAR" in the table without adding it to the GROUP-function? 我的问题:如何在表中获取“ YEAR”列而不将其添加到GROUP函数中? If I just add "year" in the GROUP-function, the Maxnumber will be split in Years to.
如果我只是在GROUP函数中添加“ year”,则Maxnumber将以Years为单位。 All I need is to add the relevant year to each line in the table (as shown in the required result).
我需要做的就是将相关年份添加到表的每一行中(如所需结果所示)。
I hope you SQL wizards can help me solving this. 我希望您的SQL向导可以帮助我解决这个问题。
thanks. 谢谢。 Br, Jakob
Br,雅各布
This part is a little redundant: 这部分有点多余:
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
You can just do this: 您可以这样做:
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
Then you can use ROW_NUMBER
to assign the row with the highest count per country a 1
: 然后,您可以使用
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
Then just do an outer select to get the rows where RN = 1
: 然后只需执行外部选择即可获得
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.