I have 3 tables with items, owners and statuses and I need to show the count of items that were sold/discarded grouped by every owner for the year passed as parameter.
I am able to get ownername and soldcount as one query and ownername and discardcount as second query but is there a way to structure so that ownername, soldcount and discardcount come in one query?
declare @QueryYear integer = 2020
--SOLD
select O1.pk_owner_id,count(P1.pk_Property_ID) as [SaleCount]
from
Item P1, Owner O1, Status S1
WHERE
(C1.fkl_owner_ID = O1.pk_owner_ID and C1.fkl_item_ID=P1.pk_item_ID and O1.isactive=1 and year(P1.dtList_Date)=@QueryYear and P1.fkl_status_ID=1)
group by
O1.pk_owner_id
--DISCARD
select O2.pk_owner_id,count(P2.pk_item_ID) as [DiscardCount]
from
item P2, owner O2, status C2
WHERE
(C2.fkl_Owner_ID = O2.pk_owner_ID and C2.fkl_item_ID=P2.pk_item_ID and O2.isactive=1 and year(P2.dtList_Date)=@QueryYear and P2.fkl_item_status_ID=2)
group by
O2.pk_owner_id
I used a Union and it gives answer in 2 columns only.