当许多列时,从每个组中选择第一行

时间:2015-08-20 04:45:08

标签: sql sql-server

假设我有一个表格如下:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Height (cm)? ");
        double height = keyboard.nextDouble();

        System.out.println("Gender (male or female? ");
        String gender = keyboard.next();
        String allowed;

        if (gender.equalsIgnoreCase("female")) {

            System.out.println("Pregnant (yes or no)? ");
            String pregnant = keyboard.next();
            if (pregnant.equalsIgnoreCase("yes")) {
                allowed = "No";
            } else {
                allowed = "Yes";
            }
        }

        if (height < 110) {
            allowed = "No";
        } else {
            allowed = "Yes";
        }

        System.out.println("Allowed to ride (yes or no)? ");
    }
}

这里,Stuff是很多专栏。请注意,地址,城市,东西都没有变化。

所以我只想返回第一行。我知道我需要做一些像

这样的事情
Name Part  Address City   ... Stuff 
Bob   X1     Y1      Z1   ... Stuff1
Bob   X2     Y1      Z1   ... Stuff1       
Bob   X3     Y1      Z1   ... Stuff1
Susan V1     Y2      Z2   ... Stuff2
Susan V2     Y2      Z2   ... Stuff2
....

但是我不确定如何在群组之后选择第一行?我看到其他帖子,但他们都是根据最小分数进行选择..因为我的专栏不是数字,我不确定它们会如何应用?

3 个答案:

答案 0 :(得分:4)

改为使用ROW_NUMBER

  

返回结果分区中行的序号   设置,从1开始,每个分区的第一行。

SELECT *
FROM (
    SELECT *,
        rn = ROW_NUMBER() OVER(PARTITION BY Name ORDER BY Part)
    FROM tbl
) AS t
WHERE rn = 1

您可以根据您对第一个的定义替换ORDER BY列。

答案 1 :(得分:1)

试试这个

 WITH CTE
    AS
    (
    SELECT ROW_NUMBER() OVER(PARTITION BY GroupColumn ORDER BY SomeColumn) as indx
        FROM YourTABLENAME
    )

    select * from CTE where indx=1

答案 2 :(得分:-1)

你可以使用top1

     SELECT top(1) Name FROM myTable GROUP_BY (NAME),

在groupby中,你不能使用aggrigrate函数显示不在groupby中的列

所以您可以选择

SELECT top(1) Name,Address, City FROM myTable GROUP_BY NAME,Address, City

SELECT top(1) Name,stuff((select ','+Address+city from myTable mt where mt.Name=myTable.Name for xmlpath('')),1,1,'') FROM myTable GROUP_BY NAME