简体   繁体   中英

Select records where the only exist 1 in a joined table

I have the following query:

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

But I get the wrong results.

I want only the postcards ID's where there is 1 record ( HAVING < 2 ) in the PST_VS_STAMP table. How can I query this?

Do the aggregation in the subquery, only on the table where you want one row. Because there is one row, you can use an aggregation function to pull out the value of any column (for one row min(col) is the column's value):

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM