日期:2014-05-17 浏览次数:20471 次
CREATE TABLE test (id INT,title INT ) INSERT INTO test SELECT 1, 3 UNION ALL SELECT 2, -3 UNION ALL SELECT 3, 4 UNION ALL SELECT 4, 5 UNION ALL SELECT 5, -4 SELECT aid FROM (SELECT a.id aid,b.id bid,a.title atitle,b.title btitle FROM test a cross JOIN test b ) a WHERE atitle+btitle=0 /* aid ----------- 2 1 5 3 (4 行受影响) */
------解决方案--------------------
似乎这样才对
难点在于有 -5 -5 5 这样奇数个的情况下
--> 测试数据:[tb] IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb] GO CREATE TABLE [tb]([id] INT IDENTITY,[col] INT) INSERT [tb] SELECT 10 UNION ALL SELECT 10 UNION ALL SELECT 10 UNION ALL SELECT -10 UNION ALL SELECT 6 UNION ALL SELECT -8 UNION ALL SELECT -6 UNION ALL SELECT -6 UNION ALL SELECT 5 UNION ALL SELECT -6 --------------开始查询-------------------------- SELECT col FROM ( SELECT [col],row_id=ROW_NUMBER() OVER(PARTITION BY [col] ORDER BY [id]) FROM [tb] WHERE [col]>0 EXCEPT SELECT ABS([col]),row_id=ROW_NUMBER() OVER(PARTITION BY [col] ORDER BY [id]) FROM [tb] WHERE [col]<0 UNION ALL SELECT [col],row_id=ROW_NUMBER() OVER(PARTITION BY [col] ORDER BY [id]) FROM [tb] WHERE [col]<0 EXCEPT SELECT -[col],row_id=ROW_NUMBER() OVER(PARTITION BY [col] ORDER BY [id]) FROM [tb] WHERE [col]>0 ) AS t /* col 5 10 10 -8 -6 -6 */