简体   繁体   English

如何编写查询以返回特定列的具有不同值的指定行数?

[英]How do I write a query to return specified number of rows with distinct values for a particular column?

I am looking to write a query to fetch 'n' number of rows with distinct values for the column PERSON_ID?我正在寻找一个查询来获取 'n' 行具有不同值的列 PERSON_ID?

SELECT  
        HDR.PERSON_ID, DTL.DETAIL_ID
FROM 
        HEADER HDR, DETAIL DTL 
WHERE 
        HDR.HEADER_ID = DTL.HEADER_ID
    AND DTL.CODE = 'SUCCESS'
ORDER BY 
    HDR.PERSON_ID

在此处输入图像描述

If I do fetch top 5, the query will return rows 1 to 5. Instead I want to get back rows 1 to 7 - this will get me 5 person rows.如果我确实获取前 5 行,查询将返回第 1 到第 5 行。相反,我想取回第 1 到第 7 行 - 这将得到 5 个人行。

You can use DENSE_RANK() to answer your question.您可以使用DENSE_RANK()来回答您的问题。 More importantly, you can learn to use proper, explicit, standard JOIN syntax.更重要的是,您可以学习使用正确、明确、标准JOIN语法。

SELECT pd.PERSON_ID, pd.DETAIL_ID
FROM (SELECT HDR.PERSON_ID, DTL.DETAIL_ID,
             DENSE_RANK() OVER (ORDER BY HDR.PERSON_ID) as ranking
      FROM HEADER HDR JOIN
           DETAIL DTL 
           ON HDR.HEADER_ID = DTL.HEADER_ID AND DTL.CODE = 'SUCCESS'
     ) pd
WHERE ranking <= 5;

You could try an inner join with the distinct PERSON_ID您可以尝试使用不同的 PERSON_ID 进行内部联接

  SELECT  HDR.PERSON_ID, DTL.DETAIL_ID
  FROM  HEADER HDR
  INNER JOIN  DETAIL DTL  ON HDR.HEADER_ID = DTL.HEADER_ID
      AND DTL.CODE = 'SUCCESS'
  INNER JOIN  (

    SELECT DISTINCT  HDR.PERSON_ID
    FROM  HEADER HDR
    INNER JOIN  DETAIL DTL  ON  HDR.HEADER_ID = DTL.HEADER_ID
      AND DTL.CODE = 'SUCCESS'
    ORDER BY   HDR.PERSON_ID

    ) T ON T.PERSON_ID = HDR.PERSON_ID
  ORDER BY   HDR.PERSON_ID

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

相关问题 如何向此查询添加显示不同行数的列? - How do I add a column that displays the number of distinct rows to this query? 如何编写 Postgres 查询以返回在特定列中以最大频率出现的值? - How do I write my Postgres query to return the value that is occuring with the maximum frequency in a particular column? 如何查询所有仅具有最高值的不同行? - How to do I query all distinct rows with only their highest values? SQL查询X个不同列值的数量,所有行 - SQL Query for X Number of Distinct Column Values, All Rows 如何选择不同的行,其中一列可能具有许多相同的值,但所有第二列均具有相同的值? - How do I select distinct rows where a column may have a number of the same values but all their 2nd columns have the same value? 如何通过列获得不同的行? - How do I get distinct rows by a column? 如何编写查询以仅返回指定的行列表? - How to write a query to return only specified list of rows? 如何编写将行号输出为列的查询? - How do I write a query that outputs the row number as a column? 如何查询具有按日期分组的不同列值的行 - How to query rows with distinct column values grouped by date 在 Postgres 中,我如何将 SQL 查询写入 select 个不同的值,但在设定的时间段内聚合 - In Postgres how do I write a SQL query to select distinct values overall but aggregated over a set time period
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM