简体   繁体   English

查询返回 SQL 中列的第一个结果?

[英]Query to return first result of a column in SQL?

In SQL, is there a simple way to return all the rows containing the top instance of a value in a column?在 SQL 中,是否有一种简单的方法可以返回包含列中值的顶部实例的所有行?

Given the table below...鉴于下表...

Size    Color    Price
S       Red      1
S       Green    4
S       Blue     7
M       Olive    45
M       Black    99
M       Orange   153
L       Purple   4
L       Red      75
L       Blue     98

I want to return...我想回来...

Size    Color    Price
S       Red      1
M       Olive    45
L       Purple   4

You can try a CTE function, and ROW_NUMBER() , to accomplish this:您可以尝试使用CTE function 和ROW_NUMBER()来完成此操作:

This accomplishes it as descending which you say in the comments这可以按照您在评论中所说的降序完成

;WITH CTE AS(
    SELECT myTable.*
    , RN = ROW_NUMBER()OVER(PARTITION BY Size ORDER BY Price DESC)
    FROM myTable 
)
SELECT Size, Color, Price FROM CTE
WHERE RN = 1

This accomplishes your desired results:这可以实现您想要的结果:

;WITH CTE AS(
    SELECT myTable.*
    , RN = ROW_NUMBER()OVER(PARTITION BY Size ORDER BY Price ASC)
    FROM myTable 
)
SELECT Size, Color, Price FROM CTE
WHERE RN = 1
ORDER BY
  CASE Size
    WHEN 'S' THEN 1
    WHEN 'M' THEN 2
    WHEN 'L' THEN 3
  END

An example SQL FIDDLE is here so you can see a demo. SQL FIDDLE示例在这里,您可以查看演示。

Influenced from: Select the first instance of a record影响自: Select 第一个实例记录

You require to partition your data to get rownums assigned to each partitioned size and then whichever is the first partition thats gonna be the result as below您需要对数据进行分区以获取分配给每个分区大小的 rownums,然后无论哪个是第一个分区,结果如下

     Select size, color, price from
         (Select Size, Color,Price, 
         row_number() 
        over (partition by size order by 
             Price) as rn
       from mytable) t where t.rn =1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM