筛选SQL中列值的组合

问题描述 投票:0回答:3

我想过滤所有具有相同属性值的人员作为另一个人我具有以下查询:

SELECT
  p1.keyValue,
  p1.Displayname,
  p2.keyValue,
  p2.Displayname,
  p1.ImportantAttrName,
  p1.ImportantAttrValue
FROM Person p1 WITH (NOLOCK)
JOIN Person p2 WITH (NOLOCK)
  ON p1.ImportantAttr = p2.ImportantAttr
WHERE p1.keyValue != p2.keyValue
AND p1.ImportantAttrValue = p2.ImportantAttrValue

使用此查询,我将获得两次所有条目,因为每个Person都将在p1和p2中。所以结果看起来像这样:

I123    Freddy Krüger   A123    The Horsemen   Moviecategorie    Horror
A123    The Horsemen    I123    Freddy Krüger   Moviecategorie    Horror

但是出于分析目的,如果我只能获得p1.keyvalue和p2.keyvalue的组合一次,而不考虑两个列中的值,那将是很好的。

到目前为止,我通过导出到excel并在那里进行清理来做到这一点,但有没有办法解决查询不能得到这个“重复”?

sql sql-server tsql
3个回答
3
投票

使用where p1.keyValue < p2.keyValue

SELECT
    p1.keyValue,
    p1.Displayname,
    p2.keyValue,
    p2.Displayname, 
    p1.ImportantAttrName,
    p1.ImportantAttrValue
FROM Person p1 WITH (NOLOCK)
INNER JOIN Person p2 WITH (NOLOCK)
    ON p1.ImportantAttr = p2.ImportantAttr
WHERE
    p1.keyValue < p2.keyValue AND       -- change is here
    p1.ImportantAttrValue = p2.ImportantAttrValue;

这将确保您不会看到重复的对。要在数字上理解其工作原理,请考虑两个关键值:12。使用条件!=1-22-1都符合该标准。但使用<只会产生1-2


2
投票

你可以转:

on p1.ImportantAttr = p2.ImportantAttr

至:

on p1.ImportantAttr = p2.ImportantAttr and p1.keyValue < p2.keyValue

整个查询可能如下所示:

SELECT
  p1.keyValue,
  p1.Displayname,
  p2.keyValue,
  p2.Displayname,
  p1.ImportantAttrName,
  p1.ImportantAttrValue
FROM Person p1 WITH (NOLOCK)
JOIN Person p2 WITH (NOLOCK)
  ON p1.ImportantAttr = p2.ImportantAttr
  AND p1.keyValue < p2.keyValue
WHERE p1.ImportantAttrValue = p2.ImportantAttrValue

0
投票

这可能是不同的方法,但可以得到预期。

使用分区计数(*):

select count(*) over(partition by Attr) as RepeatCount, * from (
select keyValue,DisplayName,ImportantAttr + ' ' +ImportantAttrValue as Attr
  from tblTest) tblTemp

根据上面的查询,您将得到如下结果

> RepeatCount    keyValue     DisplayName          Attr
> 
> 1       P321        The Ironman          Generalcategorie Test 
> 2       I123        Freddy Krüger        Moviecategorie Horror 
> 2       A123        The Horsemen         Moviecategorie Horror

从此结果中,您可以按Repeatcount> 1过滤记录

© www.soinside.com 2019 - 2024. All rights reserved.