如何在 Postgresql 中获取不同的值?

How to get Distinct Value in Postgresql?

我有一个 table approval 如下所示..

m_requisition_id    ad_wf_activity_id    bpname            designation
-------------------------------------------------------------------------
1014546             1014546              Abul Kalam Azad   Asst. Manager
1014546             1225097              Md. Hasan Zahir   Plant Manager
1014546             1229239              Md. Hasan Zahir   Plant Manager
1014546             1229240              Sayela Alam       Sr. Manager
1014546             1229241              Md. Hasan Zahir   Plant Manager
1014546             1229242              Sayela Alam       Sr. Manager

现在我需要 bpname 列的不同值基于 ad_wf_activity_id 列的最大数量,如下所示。

m_requisition_id    ad_wf_activity_id    bpname            designation
-------------------------------------------------------------------------
1014546             1014546              Abul Kalam Azad   Asst. Manager
1014546             1229241              Md. Hasan Zahir   Plant Manager
1014546             1229242              Sayela Alam       Sr. Manager

那就是 DISTINCT ON:

SELECT DISTINCT ON (m_requisition_id, bpname, designation)
       m_requisition_id, bpname, designation
FROM atable
ORDER BY m_requisition_id, bpname, designation, ad_wf_activity_id DESC;

您的数据模型未规范化,您很容易因拼写略有不同而出现问题。

您可以使用 max() 函数代替 distinct 如下所示

select m_requisition_id, max(ad_wf_activity_id), bpname, designation
from approval
GROUP BY m_requisition_id, bpname, designation

让我们在这里尝试- https://dbfiddle.uk/?rdbms=postgres_12&fiddle=73f15e1ed96f1308a5984a91b1df91e2