INTERSECT附近的语法错误

时间:2014-07-10 22:05:16

标签: sql sql-server group-by intersect

select SOURCE_SYS_CD,COUNT(*) as [COUNT BY APP] from STAGING_TRANSACTIONS
GROUP BY SOURCE_SYS_CD
ORDER BY SOURCE_SYS_CD
INTERSECT 
select SOURCE_SYS_CD,COUNT(*) as [COUNT BY APP] from TMS..TB_TRANSACTIONS
GROUP BY SOURCE_SYS_CD
ORDER BY SOURCE_SYS_CD

有谁可以告诉我上面的查询有什么问题?它们独立执行但在使用交叉时抛出错误。如何在两个表之间找到公共行?

1 个答案:

答案 0 :(得分:3)

ORDER BY是你的罪魁祸首。

它在子查询/派生表(http://msdn.microsoft.com/en-us/library/ms188385(v=sql.105).aspx)上无效。这意味着在查询结尾只应该有1个ORDER BY子句。

删除除最后一个ORDER BY之外的所有ORDER BY,你应该很好。

select SOURCE_SYS_CD,COUNT(*) as [COUNT BY APP] from STAGING_TRANSACTIONS
GROUP BY SOURCE_SYS_CD
INTERSECT 
select SOURCE_SYS_CD,COUNT(*) as [COUNT BY APP] from TMS..TB_TRANSACTIONS
GROUP BY SOURCE_SYS_CD
ORDER BY SOURCE_SYS_CD