-1

I am trying to find duplicate entries in the table but if I use Code only in the script then it will give me the duplicate entries in the table.

But I want to get all the information from the table including duplicate code.

Can someone guide me where I am doing wrong?

This results in 2 entries:

SELECT code, COUNT(code)
FROM CodeDefinition
WHERE codingSystem = '2.16' AND code='835002601'
GROUP BY code
HAVING COUNT(code) > 1

But when I tried the below script, it returns nothing.

SELECT code, COUNT(code), description, shortdescription
FROM CodeDefinition
WHERE codingSystem = '2.16' AND code='835002601'
GROUP BY code, description, shortdescription
HAVING COUNT(code) > 1

duplicate rows

Learning
  • 13
  • 2
  • Please show some sample data and define what your duplicate criteria is – Dale K Mar 08 '21 at 23:17
  • 1
    Does this answer your question? [Finding duplicate rows in SQL Server](https://stackoverflow.com/questions/2112618/finding-duplicate-rows-in-sql-server) – Dale K Mar 08 '21 at 23:20
  • Hi @DaleK, I have added a screenshot. Please help me. – Learning Mar 08 '21 at 23:22
  • Please don't use images, use formatted text. I've added a link to an answer which solves your problem. – Dale K Mar 08 '21 at 23:22
  • 2
    While asking a question, you need to provide a minimal reproducible example. Please refer to the following link: https://stackoverflow.com/help/minimal-reproducible-example Please provide the following: (1) DDL and sample data population, i.e. CREATE table(s) plus INSERT T-SQL statements. (2) What you need to do, i.e. logic and your code attempt implementation of it in T-SQL. (3) Desired output, based on the sample data in #1 above. (4) Your SQL Server version (SELECT @@version;) – Yitzhak Khabinsky Mar 08 '21 at 23:28

2 Answers2

1

You are grouping by description which is causing the issue. Please try this.

    SELECT a.code, b.cnt , a.description, a.shortdescription
    FROM CodeDefinition a
    INNER JOIN (
        SELECT code, COUNT(code) cnt
        FROM CodeDefinition
        WHERE codingSystem = '2.16' AND code='835002601'
        GROUP BY code
        HAVING COUNT(code) > 1
    ) b ON a.code = b.code
Dale K
  • 25,246
  • 15
  • 42
  • 71
Raseena Abdul
  • 516
  • 3
  • 6
0

You can try window function with cte:

with cte as
(
    SELECT code, COUNT(code)over(partition by code) CodeCount, description, 
    shortdescription
    FROM CodeDefinition
    WHERE codingSystem = '2.16' AND code='835002601'
)
select code,max(codecount),description,shortdescription from cte where CodeCount>1
group by code,description, shortdescription