简体   繁体   中英

SQL Sub-query (Where In)

I get an error with my sub-query and am not seeing what I am doing wrong. Sub-query works on it's on. There Where-In is obviously what is the problem. Also tried EXISTS.

select [ID NUMBER], [PERNO], [TITLE], [INITIALS], [SURNAME], [DATE OF BIRTH] 
from dbo.[DATASEPT002] 
WHERE [ID NUMBER] IN 
( SELECT [ID NUMBER], COUNT([PERSALNO]) AS COUNTOF 
FROM [dbo].[DATASEPT] 
GROUP BY [ID NUMBER] HAVING COUNT([PERSALNO]) >1 )

You have two columns in the subquery. Only one can be used for the IN comparison:

select [ID NUMBER], [PERNO], [TITLE], [INITIALS], [SURNAME], [DATE OF BIRTH] 
from dbo.[DATASEPT002] t
WHERE [ID NUMBER] IN (SELECT [ID NUMBER]
                      FROM [dbo].[DATASEPT] 
                      GROUP BY [ID NUMBER] 
                      HAVING COUNT([PERSALNO]) > 1
                     );

However, I would expression this more typically using window functions:

select t.*
from (select t.*, count(*) over (partition by persalno) as cnt
      from DATASEPT002 t
     ) t
where cnt > 1;

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