计算不同的行,其中另一列不相同

时间:2017-03-01 11:54:57

标签: sql sql-server

我想知道如何对NUM进行计数,其中CODE不明显?

所以计数是两个!?

CODE    NUM
T1  1001
T1  1001
T1  1001
T2  1002
T2  1002
T3  1003
T3  1003
T4  1003
T5  1004
T5  1004
T5  1004
T6  1005
T7  1005
T7  1005

3 个答案:

答案 0 :(得分:1)

 Try Below code :

 SELECT NUM , COUNT(*)
 FROM #table
 GROUP BY NUM
 HAVING COUNT(DISTINCT CODE) > 1

答案 1 :(得分:0)

试试这个:

Select count(*)
From (
  Select num
  From t
  Group by num
  Having count(distinct code) > 1
) t;

答案 2 :(得分:0)

    Create table #Tempt
(
    CODE varchar(50), 
    NUM int

)

Delete From #Tempt

 insert into #Tempt Values('T1',1001)
 insert into #Tempt Values('T1',1001)
 insert into #Tempt Values('T1',1001)
 insert into #Tempt Values('T2',1002)
 insert into #Tempt Values('T2',1002)
 insert into #Tempt Values('T2',1002)
 insert into #Tempt Values('T3',1003)
 insert into #Tempt Values('T3',1003)
 insert into #Tempt Values('T4',1004)
 insert into #Tempt Values('T5',1005)
 insert into #Tempt Values('T5',1005)
 insert into #Tempt Values('T6',1006)
 insert into #Tempt Values('T7',1007)
 insert into #Tempt Values('T7',1007) 

Select Count(*) as TotalCount From (Select Code,Num ,
(Select Count(*) From #Tempt Where code = t.code) as CountCode 
from #Tempt as t) as v Where CountCode=1