[英]Incorrect output in SQL partition query
我有一個表的初始值為:
+---------------------------------------+
| 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 |
+---------------------------------------+
我嘗試使用以下代碼在此表上運行查詢:
SELECT entity, country, mnth, SUM(reports) OVER (PARTITION BY mnth) FROM practice1;
我從這段代碼得到的輸出是:
+---------------------------------------+
| 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 |
+---------------------------------------+
預期的輸出應該是這樣的:
+---------------------------------------+
| Entity Country Month_No. Reports |
+---------------------------------------+
| FC US 10 5 |
| FC GER 10 11 |
| FC US 11 5 |
| FC GER 11 8 |
+---------------------------------------+
如何將其作為輸出?
您的問題可以通過一個簡單的group by
來解決:
SELECT entity, country, mnth, SUM(reports)
FROM practice1
GROUP BY entity, country, mnth
您按月按月匯總報表,而不是按實體,國家和月份匯總報表。 在partition by
子句中添加實體和國家/地區可以獲得所需的數字,但現在有一些重復的行,因為有多個行具有相同的實體,國家/地區和月份。 您可以添加distinct
來擺脫它們。
SELECT distinct entity, country, mnth,
SUM(reports) OVER (PARTITION BY entity, country, mnth)
FROM practice1;
你需要使用partition by
嗎? 看起來你最好只使用group by
。
SELECT entity, country, mnth, SUM(reports)
FROM practice1;
GROUP BY entity, country, mnth
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.