SQL Count function count all rows if a condition is met -
i have customer table, item table , transaction table following columns:
customer - id, name
item - id, description
transaction - id, custid (foreign key customer(id)), itemid (foreign key item(id))
using query, can me create query answer following question:
if particular customer has participated in transaction involves given itemid (ie. customer has bought particular item), return count of total number of transactions customer involved in. trick (and part cannot work out myself) how include transactions in count not involve itemid used in query.
you can solve problem in 2 steps:
write query returns relevant customers' ids. if write query subquery or cte (common table expression, i.e.
with
clause), don't need put results in temporary table.join resulting table (1) transaction table (to filter out transactions you're not interested in), group customer id (so can use aggregate functions in
select
clause), , selectcount(distinct transactionid)
.
something along these lines:
with relevantcustomers (customerid) ( select distinct customerid transactions itemid = 123 ) select t.customerid, count(distinct t.transactionid) transactions t inner join relevantcustomers rc on t.customerid = rc.customerid group t.customerid
this gives set of customers (by id) bought item 123, along total number of transactions each of these.
if interested in 1 specific customer, can add where
clause "outer" query filters customer's id.
Comments
Post a Comment