选择类别相同但整数相反的记录
Selecting records with identical categories, but opposing integers
这就是我正在使用的 table 的性质:
IF OBJECT_ID('TEMPDB..#TEMP') IS NOT NULL
DROP TABLE #TEMP
CREATE TABLE #TEMP (
CategoryA NVARCHAR(10),
CategoryB NVARCHAR(10),
CategoryC NVARCHAR(10),
IntegerA INT,
);
INSERT INTO #TEMP(CategoryA,CategoryB,CategoryC,IntegerA)
VALUES
('A','H','G',20),
('A','H','G',-15),
('F','L','C',10),
('N','U','X',12),
('K','G','G',15),
('K','G','G',-10);
SELECT * FROM #TEMP
请注意,顶部 2 行和底部 2 行具有相同的类别,但它们具有相反极性的整数。中间两行用正整数区分。
我需要一种方法来 select 所有不重复的记录(例如中间的 2 行)。我需要 select 带有负整数的记录,而不 select 计算它们的正对应部分。
在这种情况下所需的输出将是:
我试过看看我是否可以制作自己的 table 只插入我想要的记录,但我 运行 再次陷入同样的问题,我无法弄清楚如何区分所有类别都相同的记录。
嗯。 . .我想你想要:
select t.*
from #temp t
where t.integerA < 0 or
not exists (select 1
from #temp t2
where t2.A = t.A and t2.B = t.B and
t2.C = t.c and t2.integerA < 0
);
Here 是一个 db<>fiddle.
对于这个数据集,您可以只使用 row_number()
:
select categoryA, categoryB, categoryC, integerA
from (
select
t.*,
row_number() over(partition by categoryA, categoryB, categoryC order by integerA) rn
from temp t
) t
where rn = 1
这就是我正在使用的 table 的性质:
IF OBJECT_ID('TEMPDB..#TEMP') IS NOT NULL
DROP TABLE #TEMP
CREATE TABLE #TEMP (
CategoryA NVARCHAR(10),
CategoryB NVARCHAR(10),
CategoryC NVARCHAR(10),
IntegerA INT,
);
INSERT INTO #TEMP(CategoryA,CategoryB,CategoryC,IntegerA)
VALUES
('A','H','G',20),
('A','H','G',-15),
('F','L','C',10),
('N','U','X',12),
('K','G','G',15),
('K','G','G',-10);
SELECT * FROM #TEMP
请注意,顶部 2 行和底部 2 行具有相同的类别,但它们具有相反极性的整数。中间两行用正整数区分。
我需要一种方法来 select 所有不重复的记录(例如中间的 2 行)。我需要 select 带有负整数的记录,而不 select 计算它们的正对应部分。
在这种情况下所需的输出将是:
我试过看看我是否可以制作自己的 table 只插入我想要的记录,但我 运行 再次陷入同样的问题,我无法弄清楚如何区分所有类别都相同的记录。
嗯。 . .我想你想要:
select t.*
from #temp t
where t.integerA < 0 or
not exists (select 1
from #temp t2
where t2.A = t.A and t2.B = t.B and
t2.C = t.c and t2.integerA < 0
);
Here 是一个 db<>fiddle.
对于这个数据集,您可以只使用 row_number()
:
select categoryA, categoryB, categoryC, integerA
from (
select
t.*,
row_number() over(partition by categoryA, categoryB, categoryC order by integerA) rn
from temp t
) t
where rn = 1