Question

There are two tables: Purchase_Summary containing orderid, orderdate, userid

Purchase_Details containing itemid, orderid, category [this field contains the name of the category like “Books”,”Music”, to which itemid belongs] ItemPayment [this field contains the payment made for that particular itemid]

The column names are self explanatory. An orderid can have several itemids.

Question1: As an output we need a list of all orderids and their payments [remember the payment of an orderid will be sum of payment of all the itemids in that orderid]

Question2: As an output we need a list of all userid and the total payment received from them in the year 2013.

Question3: We need a list of all userids which have bought for more than 10,000 Rs. of value in 2012 but not bought at all in 2013.

Question4: As an output we need a list of all users who have in the year 2013, bought from category called le“Books” but not bought from category called “Music”.

Was it helpful?

Solution

Please check the my solution.I am getting right results from below queries but if there is still ways to optimize the solution kindly suggest me.

Ans1.

select orderid, sum(itempayment)
from purchase_detail
group by orderid;

Ans2.

select a.userid, sum(b.itempayment) as totalpayment
from purchase_summary as a
left join purchase_detail as b
on a.orderid = b.orderid
where year(orderdate) = '2013'
group by userid;

Ans 3.

select userid
from purchase_summary as a
inner join purchase_detail as b
on a.orderid = b.orderid
where year(orderdate) = '2012'
and userid not in
(select userid
from purchase_summary
where year(orderdate) = '2013')
group by userid
having sum(itempayment) > 10000;

Ans4.

select userid
from purchase_summary as a
inner join purchase_detail as b
on a.orderid = b.orderid
where year(orderdate) = '2013'   
and category = 'Book'
and userid not in
( select userid
from purchase_summary as a
inner join purchase_detail as b
on a.orderid = b.orderid
where year(orderdate) = '2013'
and category = 'Music'
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top