MAX SQL查询说明

时间:2018-02-20 05:30:01

标签: sql-server

我有以下表格

SELECT ID, Name
FROM
(
    SELECT ID, Name AS position, Name FROM Table1
    UNION ALL
    SELECT SUM(ID), Name, NULL
    FROM Table1
    GROUP BY Name
) t
ORDER BY
    position, ID;

我只需要获得一个最大任务,但下面是我的查询返回所有结果

Table1          
DATE      |TASK |APPROVAL|PROD_ID
1/02/2018 | 1   |xyz     |MT

TABLE2          
DATE     |TASK  |APRROVAL|PROD
1/02/2018|  2   |xyz     |SS
1/02/2018|  3   |xyz     |TT
1/02/2018|  4   |xyz     |MT

但我得到了所有记录

1 个答案:

答案 0 :(得分:0)

听起来你想要

select top (1) table2.task, table1.date,table1.prod_id from
 table1 join table2 on table1.approval=table2.aprroval
 Order by table2.task

EDIT;

我正确地重读了你的问题,试试这个;

select top(1) from 
(
   select * from table1
union all
   select * from table2
) as t
order by t.date