Group-By

僅將不同的 id 值與 postgresql 中的任何 aggreagte 函式相加

  • November 22, 2021

我需要你的幫助。假設我們有一個如下表

+---------------+-------+--------+----------+
|    barcode    | shop  |   id   | entrance |
+---------------+-------+--------+----------+
| 2014708941747 | shop1 |   3587 |        2 |
| 2014708941747 | shop2 |   3587 |        2 |
| 2014708941747 | shop3 |   3587 |        2 |
| 2014708941747 | shop4 |   3587 |        2 |
| 2014708941747 | shop5 |   3587 |        2 |
| 2014708941747 | shop6 |   3587 |        2 |
| 2014708941747 | shop7 |   3587 |        2 |
| 2014708941747 | shop1 |  44791 |        2 |
| 2014708941747 | shop8 |  65846 |        0 |
| 2014708941747 | shop9 |  83246 |        0 |
| 2014708941747 | shop3 |  92705 |       22 |
| 2014708941747 | shop4 |  98014 |        8 |
| 2014708941747 | shop2 | 103612 |       12 |
| 2014708941747 | shop5 | 109961 |       19 |
| 2014708941747 | shop6 | 115025 |        6 |
| 2014708941747 | shop7 | 126898 |      144 |
+---------------+-------+--------+----------+

現在我想知道給定條碼有多少數量,但id不能重複。對於上面的例子,我們的結果必須如下所示

+---------------+----------+
|    barcode    | entrance |
+---------------+----------+
| 2014708941747 |      225 |
+---------------+----------+

如果我對一個entrance=227不正確的傳統組執行此操作。有沒有什麼聚合函式可以解決這類問題?

我們可以通過內部查詢和組合來解決這個問題。但我想知道我們可以用視窗函式解決這個問題嗎?

如果每個條碼和 ID 的入口總是相同的,您可以首先按條碼和 id 分組,取最大入口,然後按條碼獲得總和分組。

SELECT x.barcode,
      sum(x.entrance) entrance
      FROM (SELECT t.barcode,
                   t.id,
                   max(t.entrance) entrance
                   FROM elbat t
                   GROUP BY t.barcode,
                            t.id) x
      GROUP BY x.barcode;

為所有值提供按條碼和 id 分區的 row_number。然後過濾所有沒有row_number = 1的行,然後求和。中提琴

with x as (
select
*
,ROW_NUMBER() over (partition by barcode, id order by entrance asc) as row_number
from yourtable
)
select 
barcode,
sum(entrance) as entrance
from x
where row_number = 1
GROUP by barcode

引用自:https://dba.stackexchange.com/questions/227000