求 SQL解决正数和负数抵消的难题
给一个表,表中有一列字段是有正有负数据,怎么将该表中正数和负数一样的数据删掉,使结果依然相等了
大家快来帮帮忙吧!!
[解决办法]
查出来了,删除自己写吧。另外你这个要求如果没有多一点的限制,容易出问题,不然如果是奇数的时候不就惨咯
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 ALLSELECT 10 UNION ALLSELECT 10 UNION ALLSELECT -10 UNION ALLSELECT 6 UNION ALLSELECT -8 UNION ALLSELECT -6 UNION ALLSELECT -6 UNION ALLSELECT 5 UNION ALLSELECT -6--------------开始查询--------------------------SELECT col FROM (SELECT [col],row_id=ROW_NUMBER() OVER(PARTITION BY [col] ORDER BY [id])FROM [tb] WHERE [col]>0EXCEPT SELECT ABS([col]),row_id=ROW_NUMBER() OVER(PARTITION BY [col] ORDER BY [id])FROM [tb] WHERE [col]<0UNION ALL SELECT [col],row_id=ROW_NUMBER() OVER(PARTITION BY [col] ORDER BY [id])FROM [tb] WHERE [col]<0EXCEPTSELECT -[col],row_id=ROW_NUMBER() OVER(PARTITION BY [col] ORDER BY [id])FROM [tb] WHERE [col]>0) AS t /*col51010-8-6-6*/