I have 2 tables.
Manufacturers
- idManufacturer
Coupons
idCoupon
idManufacturer
discountPercent
couponCode
startRange
endRange
I need to get all manufacturers along with the coupon with the greatest "discountPercent", if any are availabe for that manufacturer. Each manufacturer should only have one coupon.
This is the SQL I have, which works, besides in specific scenarios (see below):
DECLARE @maxdiscount TABLE
(
idmanufacturer INT
, discperc INT
)
INSERT INTO
@maxdiscount
SELECT
p.idmanufacturer
, max(discperc)
FROM
cp_manufacturers p
LEFT OUTER JOIN coupons c ON p.idmanufacturer = c.idmanufacturer
GROUP BY
p.idmanufacturer
SELECT
m.idmanufacturer
, m.discperc
, couponcode
FROM
@maxdiscount m
LEFT OUTER JOIN coupons c ON c.idmanufacturer = m.idmanufacturer AND c.discperc = m.discperc
The problem is when there are two coupons for a manufacturer with the SAME discountPercent, then 2 coupons are returned for that manufacturer. In this case, I only want to pull up the coupon with the larger start/end range.
I'm stuck on this part, any help would be appreciated.
Thank you.