SQL中的最后一行

时间:2018-01-15 08:57:49

标签: sql sql-server union-all

我有这样的查询

select  top 1* from table1 where organizationID= 79 order by D_Index desc
select  top 1* from table1 where organizationID= 87 order by D_Index desc
select  top 1* from table1 where organizationID= 19 order by D_Index desc

这里我试图获取表1中针对organizationID的最后数据..表示79,87和19的最后数据,并尝试与union结合,但这显示错误

select  top 1* from table1 where organizationID= 79 order by D_Index desc union all 
select  top 1* from table1 where organizationID= 87 order by D_Index desc union all 
select  top 1* from table1 where organizationID= 19 order by D_Index desc 

如果我写这个

  select  top 1* from table1 where organizationID= 79  union all 
    select  top 1* from table1 where organizationID= 87  union all 
    select  top 1* from table1 where organizationID= 19  
order by D_Index desc

然后显示第一行79和87以及最后一行19但我想要最后一行对79,87和19

任何帮助?

2 个答案:

答案 0 :(得分:7)

;WITH CTE as
(
  SELECT
    *,
    row_number() over (partition by organizationID order by D_Index desc) rn
  FROM
    table1
  WHERE organizationID in (19,79,87)
)
SELECT *
FROM CTE
WHERE rn = 1

没有CTE(根据要求)

SELECT *
FROM 
  (
    SELECT
      *,
      row_number() over (partition by organizationID order by D_Index desc) rn
    FROM
      table1
    WHERE organizationID in (19,79,87)
  ) x
WHERE rn = 1

答案 1 :(得分:3)

@ t-clausen.dk的回答是这里的方法,但是这里有一种方法可以使你当前的方法有效:

SELECT * FROM
    (SELECT TOP 1 * FROM table1 WHERE organizationID = 79 ORDER BY D_Index DESC) t1
UNION ALL
SELECT * FROM
    (SELECT TOP 1 * FROM table1 WHERE organizationID = 87 ORDER BY D_Index DESC) t2
UNION ALL
SELECT * FROM
    (SELECT TOP 1 * FROM table1 WHERE organizationID = 19 ORDER BY D_Index DESC) t3;

发生错误是因为ORDER BY无法出现在联合查询(或任何查询)的中间。但是如果我们将您的查询包装为子查询,那么我们可以对它们使用ORDER BY

同样,使用ROW_NUMBER是这里的方法,但是如果您需要使用这样的语法,则可以正确编写。