从子查询返回第二项

时间:2016-02-26 10:15:47

标签: sql-server database

我想从这个子查询返回第二项:

set GrowerNumber =(select top 1 tea_no
  from ktda_file
  where ktda_file.fosa_acno=customer.fosa_acno)

5 个答案:

答案 0 :(得分:1)

GrowerNumber = (
  select top 1
    tea_no
  from
    (
      select top 2
        tea_no
      from
        ktda_file
      where ktda_file.fosa_acno=customer.fosa_acno
    ) as a
  order by
    tea_no desc
)

答案 1 :(得分:1)

试试这个

WITH CTE AS
( 
 SELECT top 2 tea_no  from ktda_file
 WHERE ktda_file.fosa_acno=customer.fosa_acno
 ORDER BY tea_no ASC
)     
SELECT TOP 1 tea_no  FROM CTE ORDER BY tea_no DESC

答案 2 :(得分:0)

SELECT *
FROM customer
OUTER APPLY (
    SELECT
        Item1 = MAX(CASE WHEN t.RowNum = 1 THEN t.tea_no END),
        Item2 = MAX(CASE WHEN t.RowNum = 2 THEN t.tea_no END)
    FROM (
        SELECT tea_no, RowNum = ROW_NUMBER() OVER (ORDER BY tea_no)
        FROM ktda_file
        WHERE ktda_file.fosa_acno = customer.fosa_acno
    ) t
    WHERE RowNum < 3
) t2

答案 3 :(得分:0)

也许这会对你有所帮助:

(select tea_no from (select row_number() over ( order by tea_no asc) as rowID,  tea_no from ktda_file where ktda_file.fosa_acno=customer.fosa_acno)x where rowID = 2)

答案 4 :(得分:0)

嗨,你需要做这样的事情(正如Ivan所说,你的查询中没有订单,那么第二个是什么?)尽管如此,假设它是tea_no ......

GrowerNumber = (Select tea_no  from (select row_number() over (order by tea_no) as row
    from ktda_file where ktda_file.fosa_acno=customer.fosa_acno) as orderedlist
    where row = 2)