I have this sql table and rows defined in SQL Fiddle
In SUPPLIER_DETAILS table there is a field called IS_PAYABLE which will have values either null or 'Y'.
If IS_PAYABLE='Y'
, there could be one or more records for each PRODUCT_REG with different PRODUCT_NO.
E.g. PRODUCT_REG = 'HP_C20'
has two records with IS_PAYABLE='Y'
.
HP_C20 FR-A GB-A128 Y
HP_C20 FR-A GB-A098 Y
What I would like to have is if IS_PAYABLE='Y'
and if there are multiple records for one PRODUCT_REG, then I would want only either one of the record and I want all the records with IS_PAYABLE is null
.
How can I achieve this? If I did not make my requirement understandable, I will explain further.
Any help is highly appreciable.
Thanks
Syntax. SELECT column1, column2, columnN FROM table_name WHERE [condition1] AND [condition2]... AND [conditionN]; You can combine N number of conditions using the AND operator.
To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.
The LEFT JOIN condition is used to decide how to retrieve rows from table 2nd_table. If there is a row in 1st_table that matches the WHERE clause, but there is no row in 2nd_table that matches the ON condition, an extra 2nd_table row is generated with all columns set to NULL.
1 Answer. Here, LEFT JOIN is used to return all the rows from TableA even though they don't match with the rows in TableB. You can observe that WHERE tb.ID IS NULL clause; there will be no records in TableB for the particular ID from TableA.
select * from
(select a.*,
row_number() over (partition by product_reg order by product_no) as rnk
from SUPPLIER_DETAILS a
order by PRODUCT_REG)
where is_payable is null or rnk = 1;
SQLFIDDLE
In inner query I've ranked the products with the same product_reg.
In the outer query i've got only one product per product_reg(the first ranked) and all non payable products.
Try this:
SELECT s.*
FROM supplier_details s
WHERE NOT EXISTS(SELECT s1.*
FROM supplier_details s1
WHERE s.is_payable = 'Y'
AND s1.is_payable = 'Y'
AND s.product_reg = s1.product_reg
AND s.product_no < s1.product_no)
UNION
SELECT *
FROM supplier_details
WHERE is_payable IS NULL
http://sqlfiddle.com/#!4/25c52/2/0
EDIT: below code should also work(union is redundant)
SELECT s.*
FROM supplier_details s
WHERE NOT EXISTS(SELECT s1.*
FROM supplier_details s1
WHERE s.is_payable = 'Y'
AND s1.is_payable = 'Y'
AND s.product_reg = s1.product_reg
AND s.product_no < s1.product_no)
http://sqlfiddle.com/#!4/5e69b/1/0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With