Your solution is almost there - the problem is that although the value of Food_Name
is duplicated, the value of Food_ID
is not. Since your GROUP BY
clause includes Food_ID
, you're going to end up with at least one row for each distinct Food_ID
value, and since each of those rows only has a count of 1, it gets filtered out in your HAVING
clause.
Here's a small modification to your solution that should work the way you want it to:
SELECT MIN([Food_ID]) AS [Food_ID]
,[Food_Name]
,[Amount]
,COUNT(*) as Duplicate_Value
FROM [Foodie].[dbo].[Food]
GROUP BY
[Food_Name]
,[Amount]
HAVING
COUNT(*) > 1
Based on your desired output, I wasn't sure what value you wanted for Food_ID
, so you can try other aggregates than MIN()
.
If the values in the Amount
column are also distinct for each row, then you need to remove that column from your GROUP BY
clause and use an aggregate function in your SELECT
statement as well:
SELECT MIN([Food_ID]) AS [Food_ID]
,[Food_Name]
,AVG([Amount]) AS [Average_Amount]
,COUNT(*) as Duplicate_Value
FROM [Foodie].[dbo].[Food]
GROUP BY
[Food_Name]
HAVING
COUNT(*) > 1