T-SQL-返回两列中值相同但第三列中值不同的记录

时间:2018-12-04 16:47:30

标签: sql-server tsql select group-by count

给出以下示例数据:

ID    lname        fname    num
1     Jones        Mary     672
2     Jones        Mary     123
3     Johnson      Ellen    853
4     Jones        Mary     123
5     Jones        Scott    342
6     Smith        John     874
7     Anders       David    433
8     Northson     Sue      756
9     Fredricks    George   555
10    Northson     Sue      756
11    Northson     Sue      756
12    Perry        Nicole   335
11    Northson     Sue      342

我想查找所有具有多个“ num”的lname / fname对以及具有该“ num”值的行数。

因此结果集应如下所示:

lname        fname    num    count
Jones        Mary     672    1
Jones        Mary     123    2
Northson     Sue      756    3
Northson     Sue      342    1

我唯一能想到的是以下内容,但是where子句中的select返回的内容比行还多

select
    lname
    ,fname
    ,num
    ,COUNT(*)
from sampleTable
where
    (num != (select x.num
             from sampleTable x
             where x.ID != sampleTable.ID
                 and x.fname = sampleTable.fname
                 and x.lname = sampleTable.lname)   
     )
group by lname, fname, num
--having count(num) > 1
order by lname, fname, num

2 个答案:

答案 0 :(得分:2)

另一种方法是联接另一个查询并计算每个num / lname组合中不同的fname的数量:

SELECT   a.lname, a.fname, a.num, a.cnt
FROM     (SELECT   lname, fname, num, COUNT(*) AS cnt
          FROM     sampleatable
          GROUP BY lname, fname, num) a
JOIN     (SELECT   lname, fname
          FROM     sampletable
          GROUP BY lname, fname
          HAVING   COUNT(DISTINCT num) > 1) b ON a.lname = b.lname AND a.fname = b.fname

答案 1 :(得分:1)

select  lname, fname, num, 
    row_number() over(PARTITION BY lname, fname, num ORDER BY lname, fname, num) as cnt,
    row_number() over(PARTITION BY lname, fname ORDER BY lname, fname) as pairs
from  sampleTable  

返回(从我的表的临时版本中返回)

lname   fname   num cnt pairs
Jones   Mary    123 1   1
Jones   Mary    672 1   2
Jones   Scott   111 1   1
Jones   Scott   111 2   2
Jones   Scott   342 1   3
Jones   Scott   874 1   4