简体   繁体   中英

SQL - Retrieve data based upon multiple conditions

I am trying to show a list of accounts where 2 identical products, have been ordered for the same account, within the same calendar month.

Field names:

A/c number,
Order id,
Cust name,
Product,
Purchase date

I have used GROUP BY and HAVING, but I am concerned with the volume of records returned.

SELECT * 
FROM TABLE as table2 
INNER JOIN table as table1 
on table1.product = table2.product AND MONTH(table1.purchase_date) = MONTH(tabl2.purchase_date) AND YEAR(table1.purchase_date) = YEAR(table2.purchase_date)

This should do the trick.

Assuming we have no table names , and are missing datas, here an example of a query that would return what you want. Simply change the fields/table name to whatever you are using.

SELECT account_name
  FROM purchaseTable
  JOIN productTable on purchaseTable.product = productTable.id
  WHERE MONTH(purchaseTable.purchase_date) = MONTH(productTable.purchase_date)
  AND YEAR(purchaseTable.purchase_date) = YEAR(productTable.purchase_date)
  HAVING COUNT(*) = 2
  GROUP BY account_name;

I would suggest doing an inner join on the same table twice. Something like:

SELECT o1.*
FROM orders o1
INNER JOIN orders o2
    ON o1.account_num = o2.account_num
    AND o1.product_id = o2.product_id
    AND MONTH(o1.purchase_date) = MONTH(o2.purchase_date)
    AND YEAR(o1.purchase_date) = YEAR(o2.purchase_date)

I just want to point out that you have to match BOTH the months AND the years to avoid matching something purchased on 1/2014 with 1/2015

select *
from accounts
where account_id in (
    select o.account_id
    from orders as o inner join line_items as li on li.order_id = o.order_id
    group by o.account_id, li.product_id, year(o.purchase_date), month(o.purchase_date)
    having count(*) = 2
)

Easy way to get account info although you lose the purchase info.

Here's a method that keeps the info along with both order_ids and the calendar month of the orders:

select *
from
    accounts as a inner join
    (
    select
        o.account_id, li.product_id,
        year(o.purchase_date) as purchase_yr, month(o.purchase_date) as purchase_mo,
        min(o.order_id) as order_id1, max(o.order_id) as order_id2
    from orders as o inner join line_items as li on li.order_id = o.order_id
    group by o.account_id, li.product_id, year(o.purchase_date), month(o.purchase_date)
    having count(*) = 2
    ) as multiples
        on multiples.account_id = a.account_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM