选择只有count = 2

时间:2013-09-25 08:42:19

标签: sql-server-2008

- 这是代码

create table #Test (Systemtraceno nvarchar(50),Bin nvarchar(50),SwitchCode nvarchar(50),
SwitchDesc nvarchar(50),[Description] nvarchar(50))

insert into #Test 
select SystemTraceno , Bin,SwitchCode,SwitchDesc,[Description]
from(
select A.SystemTraceNo, A.BIN,'' SwitchCode, '' SwitchDesc,''[Description]
from ATM035 A 
where a.TranDate = '20130924' and  MsgType = '0210' and TerminalID = '08880001'
and A.ProcessCode in ('011000','012000','013000') and A.ResponseCode = '0000' and A.BIN <> '502265' 
--group by A.SystemTraceNo, A.BIN
)x
group by SystemTraceNo,BIN,SwitchCode,SwitchDesc,[Description]
having COUNT(SystemTraceNo)=2

update #Test set SwitchCode = (select top 1 SwitchCode from ATM027 where Bin = #Test.Bin )
update #test set SwitchDesc = (select switchname from ATM016 where SwitchCode = #test.switchcode)
update #test set [Description] = (Select top 1 Description from ATM027 where BIN = #Test.Bin )

Select * from #test order by SwitchDesc asc
drop table #test    

- , '301000', '302000', '303000'

我只是想选择具有SystemTrace数量计数= 2的行。我之前遇到了聚合问题,现在这个。希望你能帮助我。谢谢你提前

4 个答案:

答案 0 :(得分:1)

我不打算进入你的代码,但它应该是这样的:

select customers.customerId 
from customers join orders on custumers.Id = orders.customerId
group by customers.customerId
having count(orders.id)=2

见第2节:(第1节是指那可能的人。)

http://i.stack.imgur.com/aE2M3.png

答案 1 :(得分:1)

@Royi:实际上,我认为它应该是

select customers.customerId , count(orders.id) as num
from customers join orders on custumers.Id = orders.customerId
group by customers.customerId
having num=2

答案 2 :(得分:0)

where systemtraceno in (select systemtraceno from #Test group by systemtraceno having count(systemtraceno) = 2)

答案 3 :(得分:0)

我把问题解决了

group by SystemTraceNo

何时使用

COUNT(SystemTraceNo)=2

简而言之,您的插入代码应如下所示:

insert into #Test 
select A.SystemTraceno , A,Bin,'' SwitchCode,'' SwitchDesc,'' [Description]
from ATM035 A 
where a.TranDate = '20130924' and  MsgType = '0210' and TerminalID = '08880001'
and A.ProcessCode in ('011000','012000','013000') and A.ResponseCode = '0000' and A.BIN <> '502265'
group by A.BIN
having COUNT(SystemTraceNo)=2