运算符T-SQL除外

时间:2014-03-24 07:06:25

标签: sql-server tsql

任务:为在任何2个月内至少购买1次但未在所有3个月内购买的客户显示c_id和c_name。

First Month = November
Second Month = December
Third Month = January



SELECT c_id, c_name
FROM books
WHERE MONTH(order_date) = 11
INTERSECT
SELECT c_id, c_name 
FROM books
WHERE MONTH(order_date) = 12
EXCEPT
SELECT c_id, c_name
FROM books
WHERE MONTH(order_date) = 1

我现在的代码否定了第3个月,但它没有满足任务所要求的,可以互换选择任何2个月。

规则是:无计数,无子查询,无加入

1 个答案:

答案 0 :(得分:0)

我设法想出了这个。

select c_id,c_name from books where month(order_date) = 1
intersect 
select c_id,c_name from books where month(order_date) = 11
union
select c_id,c_name from books where month(order_date) = 1
intersect 
select c_id,c_name from books where month(order_date) = 12
union
select c_id,c_name from books where month(order_date) = 12
intersect 
select c_id,c_name from books where month(order_date) = 11
except
select c_id,c_name from books where month(order_date) = 1
intersect 
select c_id,c_name from books where month(order_date) = 11
intersect 
select c_id,c_name from books where month(order_date) = 12

这相当于表达式:

(Set A intersect Set B) union (Set A intersect Set C) union (Set C intersect Set B) minus (Set A intersect Set B intersect Set C)

或正如您在image中看到的那样,区域AB,AC和BC

这当然不优雅,但考虑到要求,蛮力似乎是一种有效的方法。