如何选择共享相同ID但名称不同的记录?

时间:2017-06-15 13:41:53

标签: sql sql-server tsql

我有一张如下表:

Col_Name   Col_Id  Col_Flag
  A          1        1
  A          1        2
  B          1        1
  C          2        1
  C          2        2

对于这些记录,我希望得到Col_Id由不同网Col_Name共享的结果,对于上面的示例,所需的结果是将Col_Id作为{返回{1}},因为它是1A分享的,我不希望B返回,因为只有Col_Id = 2正在使用此值。

并且,使用相同C的相同Col_Name的总数不限于Col_Id,这意味着2可能大于2。 / p>

任何建议都将不胜感激。感谢。

4 个答案:

答案 0 :(得分:2)

 SELECT COL_ID,count(distinct COL_NAME) FROM TABLE
 GROUP BY COL_ID 
 having count(distinct COL_NAME)>1

答案 1 :(得分:0)

试试这个

 SELECT COL_ID FROM test9
 GROUP BY COL_ID
 having COUNT(DISTINCT COL_Name)>1

答案 2 :(得分:0)

在col_id和WHERE子句上使用自联接将输出限制为具有不同col_name的那些情况:

select distinct
    a.col_id
from
    some_table as a
    inner join some_table as b on a.col_id=b.col_id
where
    a.col_name <> b.col_name;

答案 3 :(得分:0)

;WITH CTE(COL_NAME,COL_ID,COL_FLAG)
AS
(
SELECT 'A', 1,1 UNION ALL
SELECT 'A', 1,2 UNION ALL
SELECT 'B', 1,1 UNION ALL
SELECT 'C', 2,1 UNION ALL
SELECT 'C', 2,2
)
SELECT COL_ID,
       COL_NAME FROM
(
SELECT COL_ID,COL_NAME,
COUNT(COL_NAME)OVER(PARTITION BY COL_ID,COL_NAME ORDER BY COL_NAME) AS UNIQENAME
FROM CTE
)DT
WHERE DT.UNIQENAME=1