Postgresql

檢查數組的每個值是否相等

  • October 14, 2020

僅當具有相同 id 的所有行都具有相同的pday時,我才嘗試獲取d.id

with dif_zero as (d.id, 
date_part('day', p.docdate)::text pday
from sh_billing.dogovor d 
join sh_billing.pays p on p.dogovor_id = d.id and p.is_actual
)
select id
from 
dif_zero 
group by id
having sum(char_sal_dif) = 0 
and avg(pday::int) =  (array_agg(pday))[1]::int 
and avg(pday::int) =  (array_agg(pday))[2]::int -- and so on...

可能還有其他方法(更簡單)來了解數組中的所有元素是否彼此相等?

或者我可以在子查詢中使用視窗函式,然後只取值 = 1 的行。

select id, count(id) over(partition by id) one_day

哪種方式更好?或者也許還有其他方法可以更正確地做到這一點?

如果您想確保所有日期都相同,只需比較最小值和最大值。如果它們相同,則所有值也相同。

with dif_zero as (
 select d.id, 
        date_part('day', p.docdate)::int pday
 from sh_billing.dogovor d 
  join sh_billing.pays p on p.dogovor_id = d.id and p.is_actual
)
select id
from 
dif_zero 
group by id
having sum(char_sal_dif) = 0 -- where does char_sal_dif come from? 
  and min(pday) = max(pday) 

一種更昂貴(=更慢)但可能更容易理解的方法是將計數與不同值的計數進行比較:

having count(*) = count(distinct pday)`

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