I have some sql that will not return the rows I need unless I specify that as a criteria in the where clause. If I uncomment the part below that is commented out, it will give me the rows I want. If I leave it commented out, those rows are not returned in my result set.
Does this make sense? Can anyone see anything I’m doing wrong? Thanks.
SELECT
RTRIM(c.comp2) + '-' + l.Loc_Name,
MAX(RTRIM(g.mega_location_num) + '-' + g.mega_location_name)
FROM
mkt_share_comp c, gldm_location g, mkt_share_locs l
WHERE
RTRIM(c.comp1) = g.location_num
AND c.comp2 = l.Loc_No
AND LEN(c.comp2) = 5 AND c.is_deleted = 0 AND l.is_deleted = 0
--and g.mega_location_num = '450'
GROUP BY
RTRIM(c.comp2) + '-' + l.Loc_Name
ORDER BY
MAX(RTRIM(g.mega_location_num) + '-' + g.mega_location_name)
This comparison:
Will be doing a
MAXbased on the string value that you’re constructing. So if there are anyg.mega_location_numvalues which start with a digit greater than4(or start with4and have a second digit greater than5, etc), then that value will be theMAXvalue returned.To start to fix this, I would first switch to the ANSI join style that Kuya has suggested. I would then consider including an appropriate
ROW_NUMBER()expression to locate the “genuine” maximum value from thegtable and to be able to retrieve multiple columns from that maximal row (to allow the string construction to proceed)