我有2个表,一个是客户,另一个是订单
AutoShrink
这有效,但我想每年都这样做以获得这样的结果
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
答案 0 :(得分:0)
天蝎座是正确的,你必须使用年份功能:
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
您可以在查询的SELECT部分中使用year方法
要显示一年内未订购的所有客户,您不需要加入。您可以使用单个子选项执行此操作:
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)
)
答案 1 :(得分:0)
您需要一个列表,其中显示订单表中不的客户和年份。因此,获取所有客户的列表以及所有年份,然后减去您在订单表中找到的客户和年份:
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);