我有以下查询:
SELECT
A.POSTCARD_ID, A.STAMP_ID, B.END_DT
FROM
PST_VS_STAMP A
JOIN
STAMP B ON A.POSTCARD_ID = B.POSTCARD_ID
WHERE
B.ACCOUNT LIKE 'AA%'
AND B.END_DT = '9999-12-31'
GROUP BY
A.POSTCARD_ID, A.STAMP_ID, B.END_DT
HAVING
COUNT(A.POSTCARD_ID) < 2
但我得到了错误的结果。
我只想要HAVING < 2
表中有1条记录(PST_VS_STAMP
)的明信片ID。我该如何查询?
答案 0 :(得分:0)
在子查询中进行聚合,仅在您想要一行的表上进行。因为有一行,所以您可以使用聚合函数来提取任何列的值(对于一行min(col)
是列的值):
select s.postcard_id, vs.stamp_id, s.end_dt
from stamp s join
(select vs.postcard_id, min(stamp_id) as stamp_id
from pst_vs_stamp vs
group by vs.postcard_id
having count(*) = 1
) s
on vs.POSTCARD_ID = s.POSTCARD_ID
where s.ACCOUNT like 'AA%' and s.END_DT = '9999-12-31';