Sql 选择不同的值

Sql 选择不同的值,sql,sql-server,Sql,Sql Server,尝试获取一组记录,其中如果计数[WHO]>1,则选择[LIT]0所在的[WHO] 例如,如果[WHO]=“12082132”、“12082132”和[LIT]=0,则忽略[WHO] WHO LIT COUNT 3517015 7 1 3523687 0 1 12057744 0 2 12058316 7 1 12059820 7 1 12082132 2 2 12082132 5 1 12082132

尝试获取一组记录,其中如果计数[WHO]>1,则选择[LIT]0所在的[WHO]

例如,如果[WHO]=“12082132”、“12082132”和[LIT]=0,则忽略[WHO]

WHO        LIT  COUNT
3517015     7   1
3523687     0   1
12057744    0   2
12058316    7   1
12059820    7   1
12082132    2   2
12082132    5   1
12082132    1   3
12082132    14  1
12082132    0   1
我尝试过分组,案例陈述,但我想我是在试图得到一些不可能的东西。任何帮助都可以

预期结果

 WHO           LIT  COUNT
    3517015     7   1
    12058316    7   1
    12059820    7   1
尝试获取一组记录,其中如果计数[WHO]>1,则选择[LIT]0所在的[WHO]

这是你想要的吗

select t.*
from (select t.*, count(*) over (partition by who) as cnt
      from t
     ) t
where cnt > 1 and lit <> 0;
您可以使用“不存在”和“使用窗口”功能:

select t.*, count(*) over (partition by t.who) as cnt
from table t
where not exists (select 1 
                  from table t1
                  where t1.who = t.who and t1.lit = 0
                 );

简单的不在会起作用

SELECT * FROM #Table 
WHERE [WHO] NOT IN (
                    SELECT DISTINCT [WHO] 
                    FROM #Table
                   WHERE CASE WHEN [LIT] >= 1 THEN 0 ELSE 1  END = 1
                  )

这是一个例子,我希望它能帮助你,我认为它能做你想做的,但它有点棘手,也许能引导你找到答案,至少如果不是的话 你想要什么

drop table #testMr
drop table #checkTest
create table #testMr(who numeric, lit numeric, count_x numeric)
create table #checkTest(who numeric, lit numeric, count_x numeric,countWho numeric)

insert into #testMr values(3517015,7,1)
insert into #testMr values(3523687,0,1)
insert into #testMr values(12057744,0,1)
insert into #testMr values(12058316,7,1)
insert into #testMr values(12082132,1,3)
insert into #testMr values(12082132,14,1)
insert into #testMr values(12082132,7,1)
insert into #testMr values(12082132,0,1)

insert into #checkTest
select who,sum(lit) as [lit],sum(count_x) as [CountX],count(who) as [CountWho] from #testMr  
where who in(select b.who from #testMr as b where b.lit<>0) group by who having count(who)>1

if(select count(*) from #checkTest)>0
begin
--there are some invalid values so we filter by the lit<>0 and remove the invalid ones.
    select * from #testMr where lit<>0 and who not in(select b.who from #checkTest as b)
end
else
begin
--'All values are Ok and we filter by the count who.'
    select who,sum(lit) as [lit],sum(count_x) as [CountX] from #testMr group by who having count(who)>1
end

请显示所需的结果。如果[LIT]=0,是否要忽略整个[WHO]?或者只是[LIT]=0的特定行?是。那正是我想要的?在我上面的列表中,我不希望返回12082132或类似值,但我希望返回12058316或类似值,您希望返回12058316的所有记录,对吗?或者只是列[谁]?正确。12058316的所有记录。这不会返回lit=0或与预期结果不匹配的WHO。