SQL 有计数逻辑

SQL Having count logic

我需要有关 HAVING COUNT 的帮助,我有以下数据结果集:

CREATE TABLE #tmpTest1 (Code VARCHAR(50), Name VARCHAR(100))

INSERT INTO [#tmpTest1]
(
    [Code],
    [Name]
)
SELECT '160215-039','ROBIN'
UNION ALL SELECT '160215-039','ROBIN'
UNION ALL SELECT '160215-046','SENGAROB'
UNION ALL SELECT '160215-046','BABYPANGET'
UNION ALL SELECT '160215-045','JONG'
UNION ALL SELECT '160215-045','JAPZ'
UNION ALL SELECT '160215-044','AGNES'
UNION ALL SELECT '160215-044','AGNES'
UNION ALL SELECT '160215-041','BABYTOT'
UNION ALL SELECT '160215-041','BABYTOT'
UNION ALL SELECT '160215-041','BABYTOT'

我只想显示具有相同 code 但不同 name 的行,因此在这种情况下,我的预期结果如下,因为它们具有相同的代码但名称不同:

160215-045  JAPZ
160215-045  JONG
160215-046  BABYPANGET
160215-046  SENGAROB

但是当我尝试 group 两列然后使用 having count 时,下面是我的查询:

SELECT [Code], [Name] FROM [#tmpTest1] 
GROUP BY [Code], [Name] HAVING COUNT([Code]) > 1

它给了我错误的结果,下面的行具有相同的代码和名称,这与我想要的相反。

160215-044  AGNES
160215-041  BABYTOT
160215-039  ROBIN

如何获得预期的输出?

在此先致谢,如有任何帮助,我们将不胜感激。

我相信这个查询会给你想要的结果,虽然你原来的问题有点不清楚。

SELECT t1.[Code], t1.[Name]
FROM [#tmpTest1] t1
INNER JOIN
(
    SELECT [Code]
    FROM [#tmpTest1] 
    GROUP BY [Code]
    HAVING COUNT(DISTINCT [Name]) > 1
) t2
    ON t1.[Code] = t2.[Code]

按照下面的 link 进行 运行 演示:

SQLFiddle

来自您的评论

if there is 1 different name for the codes , i want to show those records for me to know that there is one differs to others..

这听起来像一个 exists 查询,因为您想检查是否存在具有相同代码但名称不同的另一行。

select * from [#tmpTest1] t1
where exists (
  select 1 from [#tmpTest] t2
  where t2.code = t1.code
  and t2.name <> t1.name
)

如果您想要具有相同代码和名称的行,则使用 window 函数:

select t.*
from (select t.*, count(*) over (partition by code, name) as cnt
      from #temptest1 t
     ) t
where cnt >= 2;