[英]Incorrect output in SQL partition query
I have a table with the initial values as: 我有一个表的初始值为:
+---------------------------------------+
| Entity Country Month_No. Reports |
+---------------------------------------+
| FC US 10 2 |
| FC US 10 3 |
| FC GER 10 4 |
| FC GER 10 7 |
| FC US 11 5 |
| FC GER 11 8 |
+---------------------------------------+
I tried running a query on this table using this code: 我尝试使用以下代码在此表上运行查询:
SELECT entity, country, mnth, SUM(reports) OVER (PARTITION BY mnth) FROM practice1;
The output that I got from this code was: 我从这段代码得到的输出是:
+---------------------------------------+
| Entity Country Month_No. Reports |
+---------------------------------------+
| FC US 10 16 |
| FC US 10 16 |
| FC GER 10 16 |
| FC GER 10 16 |
| FC US 11 13 |
| FC GER 11 13 |
+---------------------------------------+
The expected output should be like this: 预期的输出应该是这样的:
+---------------------------------------+
| Entity Country Month_No. Reports |
+---------------------------------------+
| FC US 10 5 |
| FC GER 10 11 |
| FC US 11 5 |
| FC GER 11 8 |
+---------------------------------------+
How do I get this as output? 如何将其作为输出?
Your problem can be solved with a simple group by
: 您的问题可以通过一个简单的
group by
来解决:
SELECT entity, country, mnth, SUM(reports)
FROM practice1
GROUP BY entity, country, mnth
You're summing reports by month, not by entity, country, and month. 您按月按月汇总报表,而不是按实体,国家和月份汇总报表。 Adding entity and country to the
partition by
clause gets you the numbers you want, but now there are some duplicate rows because there are multiple rows with the same entity, country, and month. 在
partition by
子句中添加实体和国家/地区可以获得所需的数字,但现在有一些重复的行,因为有多个行具有相同的实体,国家/地区和月份。 You can add distinct
to get rid of those. 您可以添加
distinct
来摆脱它们。
SELECT distinct entity, country, mnth,
SUM(reports) OVER (PARTITION BY entity, country, mnth)
FROM practice1;
Do you need to use partition by
? 你需要使用
partition by
吗? Seems like you're better off just using group by
. 看起来你最好只使用
group by
。
SELECT entity, country, mnth, SUM(reports)
FROM practice1;
GROUP BY entity, country, mnth
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.