Select min(price) Group By sku = duplicates
This is driving me nuts, I can't crack it or find the information I need to crack it....
INSERT INTO tbl_product_production
(sku,[cost del exc],distributor)
SELECT LTRIM(RTRIM(LOWER(sku))), MIN([cost del exc]),distributor
FROM tbl_product_stage T1
WHERE (NOT EXISTS (SELECT LOWER(RTRIM(LTRIM(sku)))
FROM tbl_product_production T2
WHERE (lower(rtrim(ltrim(T1.sku)))) = (LOWER(RTRIM(LTRIM(T2.sku))))))GROUP BY LTRIM(RTRIM(LOWER(sku))), distributor
This works, however if I have a part number (6677), which is available from three different distribution houses, I want it to insert into the table the lowest price, the sku part number and the distributor which has the lowest price.... BUT it inserts three records, one for each distributor, not just one...
INSERT INTO tbl_product_production
(sku,[cost del exc])
SELECT LTRIM(RTRIM(LOWER(sku))), MIN([cost del exc]),distributor
FROM tbl_product_stage T1
WHERE (NOT EXISTS (SELECT LOWER(RTRIM(LTRIM(sku)))
FROM tbl_product_production T2
WHERE (lower(rtrim(ltrim(T1.sku)))) = (LOWER(RTRIM(LTRIM(T2.sku))))))GROUP BY LTRIM(RTRIM(LOWER(sku)))
If I run this it works as it should... but I dont get the distributor detail.
I thought of running an insert only inserting the sku, then running an update afterwards, however it is SOOOOO slow and I should have to right?
I'm sure I am missing something fundemental....... Any help greatfully received... Stuart.
|