Original content

Protected by Copyscape Plagiarism Checker

Saturday, May 1, 2010

SQL Query to sum and compare a field’s value based on relationship

Let the tables be,

Table: delivery_challan

primary key: dcno

Table: invoice_entry

Foreign key: dcno

dcno recqty
1 5
2 5
dcno desqty
1 2
1 3
2 3

Scenario: we have to sum the ‘desqty’ of the invoice_entry on ‘dcno’ wise and should compare with the ‘recqty’ of delivery_challan on ‘dcno’ wise and should show only the records of the ‘delivery_challan’ for which ‘recqty’ is greater than the sum of corresponding dcno’s ‘recqty’.

I am dam sure, you can’t understand my English. Just try the query and find the result.

SELECT * from delivery_challan where delivery_challan.recqty > (select sum(desqty) from invoice_entry where invoice_entry.dcno=delivery_challan.dcno);

No comments:

Post a Comment