简体   繁体   中英

Mysql query select customers with no orders in each year

i have 2 table's one with customers and one with orders

SELECT customers.customer_name, orders.order_date
FROM customers
Left
Join orders on (customers.customer_id = orders.customer_id)
WHERE not orders.customer_id IN (SELECT customer_id from orders where Year(order_date) = Year(@Parameter1)) 
and not orders.order_date is null

this works but i want to do this for each year to get somthing like this as result

|Year  | customer_id |
|2010  | 1           |
|2010  | 2           |
|2011  | 2           |
|2011  | 3           |
|2012  | 1           |

Scorpio is sort of right, you do have to use the year function:

SELECT Year(orders.order_date), customers.customer_id 
FROM customers 
LEFT JOIN orders
ON (customers.customer_id = orders.customer_id) 
WHERE NOT orders.customer_id 
IN (
    SELECT customer_id 
    FROM orders 
    WHERE Year(order_date) = Year(@Parameter1)
) 
AND 
NOT orders.order_date is NULL

You can use the year method in the SELECT section of your query

Update:

To display all the customers who didn't order in a year, you don't need the join. You can do it with a single subselect:

SELECT @Parameter1 AS Year, customer_id 
FROM customers 
WHERE customers.customer_id NOT IN (
    SELECT customer_id 
    FROM orders 
    WHERE Year(order_date) = Year(@Parameter1)
)

You want a list showing customers and years that are not present in the orders table. So get a list of all customers combined with all years and then subtract the customers and years that you find in the orders table:

select o.yr, c.customer_id
from customers c
cross join (select distinct year(order_date) as yr from orders) o
where (c.customer_id, o.yr) not in (select customer_id, year(order_date) from orders);

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