[英]How to select all records from one table that do not exist in particular year?
the table looks like this 桌子看起来像这样
num Year
1 | 2014
2 | 2014
3 | 2014
2 | 2015
4 | 2015
5 | 2015
6 | 2015
I would like my query to return 我希望查询返回
4 | 2014
5 | 2014
6 | 2014
1 | 2015
3 | 2015
from 1 to 6, the number that is not used in particular year. 从1到6,特定年份未使用的数字。
Generate the all the combinations and then take out the ones that exist: 生成所有组合,然后取出存在的组合:
select n.num, y.year
from (select distinct num from t) n cross join
(select distinct year from t) y left join
t
on t.num = n.num and t.year = y.year
where t.num is null;
Note that year
is a bad name for a column in SQL Server because it is the name of a function and a keyword (think datepart()
). 请注意,
year
是SQL Server中列的错误名称,因为year
是函数和关键字的名称(请考虑datepart()
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.