【问题标题】:Selecting records with identical categories, but opposing integers选择具有相同类别但整数相反的记录
【发布时间】:2020-07-21 10:37:26
【问题描述】:

这是我正在使用的表的性质:

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 行具有相同的类别,但是它们具有相反极性的整数。中间 2 行用正整数区分。

我需要一种方法来选择所有不重复的记录(例如中间的 2 行)。我需要选择带有负整数的记录,而不选择它们的正对应部分。

在这种情况下,所需的输出是:

我尝试查看是否可以创建自己的表,该表只插入我想要的记录,但我再次遇到了同样的问题,我无法弄清楚如何区分所有类别都相同的记录。

【问题讨论】:

    标签: sql sql-server tsql ssms greatest-n-per-group


    【解决方案1】:

    嗯。 . .我想你想要:

    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 是一个 dbfiddle。

    【讨论】:

    • 这似乎有效!谢谢你。我选择了另一个答案,因为这是我将使用的解决方案
    【解决方案2】:

    对于这个数据集,你可以使用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
    

    【讨论】:

      猜你喜欢
      • 2021-03-22
      • 1970-01-01
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 2013-05-29
      相关资源
      最近更新 更多