I have 4 tables: Tenant, Tenant_Vendor_Relationship, Tenant_Sell, Vendor_Sell
Type in tenant table shows whether its a vendor or tenant.
I want to write a query which will return count based on following conditions input to query is tid (tenant Id):
If:
tidis present inTenant_Vendor_Relationshipfollow below steps otherwise return 0.If type of tenant is
tenantthen return count fromTenant_Sell.If type of tenant is
vendorand at least one row for columntenant_initiatorinTenant_Vendor_Relationshipfor that:tidisYthen return count fromTenant_Sell, else fromVendor_Sellwithvid=:tid.
CREATE TABLE Tenant(tid int, name varchar(50), type varchar(50))
CREATE TABLE Tenant_Vendor_Relationship(relid int, tid int, vid int,
tenant_initiator varchar(50))
CREATE TABLE Tenant_Sell(sid int, tid int)
CREATE TABLE Vendor_Sell(sid int, vid int)
INSERT INTO Tenant (tid, name, type)
VALUES (1, 'SSK','tenant'),
(2, 'PK group','tenant'),
(3,'JD','tenant'),
(4, 'JP Morgan','vendor'),
(5, 'Toyota','vendor'),
(6,'SAMSUNG','vendor');
INSERT INTO Tenant_Vendor_Relationship(relid , tid , vid ,tenant_initiator)
VALUES (1, 1, 4,'Y'),
(2, 1, 5,'N'),
(3, 2, 4,'Y'),
(4, 4, 5,'Y'),
(5, 6, 5,'N');
INSERT INTO Tenant_Sell(sid, tid)
VALUES (1, 1),
(2, 1),
(3, 1),
(4, 2),
(5, 3);
INSERT INTO Vendor_Sell(sid, vid)
VALUES (1, 4),
(2, 6),
(3, 5),
(4, 4),
(5, 5);
Example:
For input
tid = 1, as the type istenantin tenant table and two relationship exists inTenant_Vendor_Relationship, so it should return count fromTenant_Sell. That is3.For input
tid = 4, as the type isvendorin tenant table and one relationship exists inTenant_Vendor_Relationshipandtenant_initiatorisY, so it should return count fromTenant_Sell. That is0.For input
tid = 5, as the type isvendorin tenant table and zero relationship exists inTenant_Vendor_Relationship, so it should return count0.For input
tid = 6, as the type isvendorin tenant table and one relationship exists inTenant_Vendor_Relationshipandtenant_initiatorisNso it should return count fromVendor_Sellwherevid=:tid. That will return1.