下面的查询:, v4 E, C, \4 |/ i$ f
SELECT i_adgroup_id, i_category_id. ]" y9 H! W% K/ p+ Z
FROM adgroupcategories_br 6 j" q7 _* A% `2 o WHERE i_adgroup_id IN% {) J! M+ y( ~$ U5 u: \) g5 P( ]' Y
( " X( F; O( \& R8 }& K( n" S SELECT i_adgroup_id % ~' y/ N8 r7 n- D" S; r' r k5 M FROM adgroupusers_br: `! R3 z% h' H4 [* H
WHERE i_user_id = 103713 + a0 c! m9 c+ {) P ) 6 J) n f. h" k8 A7 Q+ e9 c GROUP BY i_adgroup_id, i_category_id; 1 v! m" U- c2 V( s给我这样的结果:# ]# f5 R+ `8 \9 B% `$ F- l" g
i_adgroup_id integer | i_category_id smallint I. x( _ q& a9 T) p ---------------------|-----------------------6 i+ ?& g9 G1 i d6 g4 i
15938 | 2 : N0 g Q' p( @4 D$ [+ @2 s 15938 | 3 + r! L; r- y$ M: J9 P: u+ } 15938 | 40 M; ^3 U( s: |% \& M
15942 | 11 \% O% U+ S+ H8 x. R
15942 | 2 7 a5 v1 h( |& ^7 K我想要的是这样的结果: 8 _ E# {1 z* k: B/ b+ ] i_adgroup_id integer | i_category_id smallint[]: y1 B, r3 z- i6 _5 M9 @; ^7 B7 E, ]7 }
---------------------|----------------------- & }1 W, c7 C* D 15938 | { 2, 3, 4 }6 u( Q$ |0 R/ Q" E6 b
15942 | { 1, 2 } 1 N/ t+ ]9 Q- L) G$ t8 H+ m4 F如何更改原始SQL查询以得到上面的结果?* k# f. l' @2 K9 K) m L
4 s6 o! H, B1 O4 f/ ^1 B 解决方案: * o/ v( Q& ]0 Q/ l0 b! r , g. b4 L9 J$ y. W
# u) E. n+ h7 x7 y* n4 |! F0 D
7 Y; w' x! ~6 l7 R. t 您要使用array_agg,这应该可以工作:+ n' a i% @) i/ F
SELECT i_adgroup_id, array_agg(i_category_id)# R1 M7 C/ {& |! T
FROM adgroupcategories_br$ j# e. N( h5 S# h) X5 {
WHERE i_adgroup_id IN ; T. F# }: F$ Z/ q* {# S- C$ @( ' [! v+ R( X \ SELECT i_adgroup_id : r0 }* ^) h1 }* W FROM adgroupusers_br7 s/ z/ R" \& g' I' s+ r, L
WHERE i_user_id = 103713 1 t0 M6 w' P5 m0 g/ B)( R. ?9 ]2 {8 h8 M: }4 N
GROUP BY i_adgroup_id;+ J. }9 h6 H h; f9 ~/ L. i
请注意,i_category_id不再存在,GROUP BY因为它正在聚合。