【问题标题】:How to Find Unique Rows without GroupBy, Distinct如何在没有 GroupBy、Distinct 的情况下查找唯一行
【发布时间】:2019-11-15 22:43:35
【问题描述】:

我有一个 SQL 字段,我只想根据 FamilyType 的值出现在我的 sql 查询结果中的字段中。

所以当家庭类型为3B 时,我希望出现FamilyID

我不想有重复的行(不使用 distinctgroup bywhere clause = 3B)。

这些是我在表中的字段:Family

字段: MemberID, FamilyID, FamilyType.

所以上面的字段顺序有2行:

  1. 3400, 233, 3B
  2. 3400, null, ZH
    select MemberID,  
     CASE WHEN FamilyType = '3B' THEN FamilyID 
     ELSE '' END AS FamilyIDFinal
    from Family

这仍然会产生 2 行。我愿意:

  1. 3400, 233

代替:

  1. 3400, 233
  2. 3400,空

任何指针表示赞赏。

【问题讨论】:

  • "不使用 distinct 或 groupby 或 where 子句 = '3B'" -- 换句话说,没有真正使用 SQL...为什么会有这样的限制?
  • 为什么不简单地select MemberID, FamilyType from Family where FamilyType = '3B'
  • 这毫无意义。如果要从 select 语句中排除行,请使用 where 子句。

标签: sql sql-server select subquery


【解决方案1】:

嗯,理论上你可以:

select top (1) with ties
  MemberID,
  CASE WHEN FamilyType = '3B' THEN FamilyID ELSE 0 END AS FamilyIDFinal
from Family
order by row_number() over(partition by MemberID order by case FamilyType when '3B' then 1 else 2 end);

但是,使这个查询高效将是相当困难的。像(MemberID, FamilyType) include (FamilyID) 这样的索引应该可以工作,但它会与这个单一查询的逻辑紧密耦合。根据个人经验,top (1) with ties 通常是万不得已的解决方案,当其他一切都无法交付时。通常最好修改数据模型。

【讨论】:

  • 这就是我要找的。我正在使用带有子查询的 With SQL 子句 - 以及上面列出的基本代码示例,仅提取特定行而不重复。谢谢。
猜你喜欢
  • 2020-05-11
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
相关资源
最近更新 更多