Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
减去两个结果集SQL_Sql_Sql Server 2012 - Fatal编程技术网

减去两个结果集SQL

减去两个结果集SQL,sql,sql-server-2012,Sql,Sql Server 2012,如何通过在这两个结果集之间进行减法运算来获得a不存在和不在对这两个结果集不返回任何内容。但是我想把a返回。求救 嗯。这很棘手,因为您需要考虑计数。一种方法是: Result1 Result2 a a b b a 这并不能完全返回您想要的内容,但可能已经足够了。另一种方法将使用行编号(): 对于标准SQL,您可以使用,除了all运算符: select r1.col from (select col, row_number() over (p

如何通过在这两个结果集之间进行减法运算来获得
a
<代码>不存在和
不在
对这两个结果集不返回任何内容。但是我想把
a
返回。求救

嗯。这很棘手,因为您需要考虑计数。一种方法是:

Result1     Result2
a           a
b           b    
a
这并不能完全返回您想要的内容,但可能已经足够了。另一种方法将使用
行编号()


对于标准SQL,您可以使用
,除了all
运算符:

select r1.col
from (select col, row_number() over (partition by col order by col) as seqnum
      from result1
      group by col
     ) r1 left join
     (select col, row_number() over (partition by col order by col) as seqnum
      from resuult2
      group by col
    ) r2
    on r1.col = r2.col and r1.seqnum = r2.seqnum
where r2.col is null;
SQLFiddle:


请注意,如果在
table\u one
中有
a
两次,上述查询也会返回它两次。

您使用的是哪个版本的SQL?假设第一个结果集有三条
a
记录。那么您想要什么输出?@Tim Biegeleisen,SQL 2012。如果
Result1
有3个
a
s,则应返回2个
a
s。谢谢您,先生!。尝试了第一种方法并给出了预期的结果。方法二,还有待尝试。谢谢你的回答。执行时出现错误,
不支持EXCEPT运算符的“ALL”版本
。原因是什么?@Isuru:您使用的是哪种DBMS?
SQLServerManagementStudio 2012
。如果它能工作的话,我认为您的方式更容易处理,先生。@Isuru:那么看来SQL Server不支持ALL@Isuru:Postgres,如SQLFIDLE中所示。我知道DB2、ApacheDerby和HSQLDB也支持它。可能还有其他人。
select r1.col
from (select col, row_number() over (partition by col order by col) as seqnum
      from result1
      group by col
     ) r1 left join
     (select col, row_number() over (partition by col order by col) as seqnum
      from resuult2
      group by col
    ) r2
    on r1.col = r2.col and r1.seqnum = r2.seqnum
where r2.col is null;
select *
from table_one
except all
select * 
from table_two