sql-server SQL,以确保组合类型的count(*)>1

6tr1vspr  于 2022-10-31  发布在  其他
关注(0)|答案(4)|浏览(163)
SELECT 
    COUNT(*), PERSON_ID
FROM 
    SGT_PERSON_ACCOUNT SPAT(NOLOCK)
WHERE
    ACCOUNT_STATUS_VALUE IN ('ACTV','RFND')
GROUP BY 
    PERSON_ID 
HAVING 
    COUNT(PERSON_ID) > 1

在这里,我只是想确保它返回的记录计数应该大于一个,其帐户状态应该是任何一个'ACTV'和'RFND'状态的组合。
但是,如果任何人员ID的“RFND”状态仅为“ACTV”,则不应返回。
示例:
人员标识1100具有两个状态均为“ACTV”的帐户。人员标识1200具有两个状态均为“RFND”的帐户。人员标识1300具有两个状态均为“ACTV”和“RFND”的帐户。
我的查询应仅返回1300个人员标识

lvjbypge

lvjbypge1#

选择每种类型仅具有一个状态值的所有人员:

SELECT PERSON_ID
FROM SGT_PERSON_ACCOUNT
WHERE ACCOUNT_STATUS_VALUE = 'ACTV'
GROUP BY PERSON_ID 
HAVING COUNT(PERSON_ID) = 1  

INTERSECT

SELECT PERSON_ID
FROM SGT_PERSON_ACCOUNT
WHERE ACCOUNT_STATUS_VALUE = 'RFND'
GROUP BY PERSON_ID 
HAVING COUNT(PERSON_ID) = 1
qnakjoqk

qnakjoqk2#

SELECT COUNT(distinct ACCOUNT_STATUS_VALUE), PERSON_ID
FROM SGT_PERSON_ACCOUNT SPAT(NOLOCK)
WHERE ACCOUNT_STATUS_VALUE IN ('ACTV','RFND') --this where clause might be optional according to my understanding
GROUP BY PERSON_ID 
HAVING COUNT(distinct ACCOUNT_STATUS_VALUE) > 1
rbpvctlc

rbpvctlc3#

如果您只需要确定哪些PERSON_ID符合您的标准:

SELECT PERSON_ID
FROM SGT_PERSON_ACCOUNT
GROUP BY PERSON_ID
HAVING COUNT(DISTINCT ACCOUNT_STATUS_VALUE) > 1

如果您需要获取关联信息沿着他们的PERSON_ID:

SELECT * 
FROM SCT_PERSON_ACCOUNT
WHERE PERSON_ID IN (
    SELECT PERSON_ID
    FROM SGT_PERSON_ACCOUNT
    GROUP BY PERSON_ID
    HAVING COUNT(DISTINCT ACCOUNT_STATUS_VALUE) > 1
    )
xqnpmsa8

xqnpmsa84#

SELECT 
COUNT(ACCOUNT_STATUS_VALUE) as CT, PERSON_ID
FROM 
SGT_PERSON_ACCOUNT SPAT(NOLOCK)
WHERE
ACCOUNT_STATUS_VALUE IN ('ACTV','RFND')
GROUP BY 
PERSON_ID 
HAVING 
COUNT(DISTINCT ACCOUNT_STATUS_VALUE) > 1

编辑

这里有一个证明,在SELECT中使用COUNT(*)不会改变任何事情。

if object_id('tempdb..#temp') is not null drop table #temp

create table #temp ( PERSON_ID int, ACCOUNT_STATUS_VALUE varchar(20) null, SOMETHING varchar(6))

insert into #temp (PERSON_ID,ACCOUNT_STATUS_VALUE, SOMETHING) values
(1100,'ACTV','A'),
(1100,'ACTV','B'),
(1300,'ACTV','C'),
(1300,'RFND','D')

SELECT 
    COUNT(*), PERSON_ID
    FROM 
    #temp (NOLOCK)
    WHERE
    ACCOUNT_STATUS_VALUE IN ('ACTV','RFND')
    GROUP BY 
    PERSON_ID 
    HAVING 
    COUNT(DISTINCT ACCOUNT_STATUS_VALUE) > 1

相关问题