【问题标题】:SQL get first reord in each of a list of recordsSQL 获取每个记录列表中的第一条记录
【发布时间】:2021-08-31 16:47:07
【问题描述】:

帮助!对 SQL 来说有点新。几年来我一直在使用简单的语句,但我需要一些高级帮助。我知道这是可以做到的,并且会节省我的时间。

这是我尝试查找结果的示例:

select top 1 apples, color from fruits
where apples in ('gala', 'fuji', 'granny')
and (inStock is not null and inStock <> '')

在上面的查询中,我会得到“gala”苹果中的第一种颜色,仅此而已。我想要的是'gala'中的第一个颜色,'fuji'中的第一个,'granny'中的第一个等等。

InStock 没有那么重要 - 它只是搜索结果中的一个附加过滤器。

我想要的是一个两列的列表。左列是苹果类型,右列是每种苹果类型的第一个颜色结果。

【问题讨论】:

  • 请注明您的数据库管理系统的版本。
  • 试试 GROUP BY 子句

标签: sql greatest-n-per-group


【解决方案1】:

您可以使用row_number() 窗口排名功能以特定顺序序列化苹果智能颜色。然后通过选择第一行从每个组中选择第一个。

with cte as 
(
    select apples, color ,row_number()over(partition by apples order by apples) rn from fruits
    where apples in ('gala', 'fuji', 'granny')
    and (inStock is not null and inStock <> '')
)
select apples, color from cte where rn=1

【讨论】:

  • 不客气@BradH。最良好的祝愿。
【解决方案2】:

我认为您在这里可能遇到的一个问题是“第一”的概念。颜色是一个分类变量,除了少数例外,表格通常不会将含义附加到“第一个”或“最后一个”值。如果您一心想要返回每个水果的第一行,那么获得结果的一种简单方法是使用union all

SELECT top 1 apples, color from fruits where apples = 'gala'
UNION ALL 
SELECT top 1 apples, color from fruits where apples = 'fuji'
UNION ALL
SELECT top 1 apples, color from fruits where apples = 'granny'

【讨论】:

  • 感谢您的帮助!对我来说,这个解决方案的唯一问题是这只是一个例子。实际上,“苹果”的列表超过 100 个。我不想一遍又一遍地写那个声明。第一个响应效果很好。
猜你喜欢
  • 2014-08-29
  • 1970-01-01
  • 2014-06-01
  • 2016-11-16
  • 2019-12-28
  • 2013-07-23
  • 2021-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多