Skip to content
Advertisement

Trouble dealing with max() function in SQL Server

The whole code is part of a stored procedure. I have two pieces of code:

This one works fine. On the line

this particular code is producing the output:

and the other one:

This is not working correctly. I get an error:

Subquery returned more than 1 value

on this line

Independently it produces this output:

Column and table names are dummy. can someone help please?

Edit

Sample data

Eng table

Del table

I need to pull data from these 2 tables.

This is the output I need:

Logic is pull latest version from eng table and map them to rows in del table and find the latest version there as well.

Advertisement

Answer

I think you have an typo in the following line

where it reads WHERE D.DelId=d.DelId

You are comparing the same column from the same table,
so both queries are not doing the same thing.

EDIT

Since you do not believe me, I made a DBFiddle with your sample data.

I have your query, that returns the error,
and I have the query where I change the where clause I as said above, which works.

EDTI 2

In the comment you asked how this works, I will try to explain

your mainquery has an alias called D

in your where clause you have a subquery, and in that subquery you also have an alias called d

put together :

So, what you probably expect is that the database takes the DelID from the subquery (alias d) and compares it with the DelId from the main query (alias D).

But that is not what is happening, because alias D and d are the same, the database does not looks for the value in the main query, because it has a d right here in the subquery.
You might just as well have written where 1=1
Therefor the group by finds 2 distinct rows (using your sample data) and thus returns 2 MAX values, hence the error.

What I did was give the subquery another alias `D2′ which means that the database will now compare the value from D.DelID with D2.DelID, which is what you want.

I hope this is clear now

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement