SQL JOIN同一个表

时间:2018-04-27 16:04:08

标签: sql ms-access

我有一张表" ID","序列","状态":

    ID | Seq | Status
    ======================
    10 | 001 | 010
    10 | 002 | test
    10 | 003 | 005
    11 | 001 | 010
    11 | 002 | 338

我的查询结果应该给我一个完整的表格以及一个额外的列,其中包含相应ID的最高序列的状态:

    ID | Seq | Status | LStatus
    ======================
    10 | 001 | 010    | 005
    10 | 002 | test   | 005
    10 | 003 | 005    | 005
    11 | 001 | 010    | 338
    11 | 002 | 338    | 338

我不知道怎么做。我喜欢这样的事情:

SELECT a.*, b.status as lstatus
FROM table a
left join (select top 1 b.status from table b order by b.seq DESC) 
on a.id = b.id

希望你能帮助我:)。

提前致谢!!!

4 个答案:

答案 0 :(得分:3)

您应该使用max by group作为子查询并加入基表

  SELECT a.*, b.status as t.lstatus
  FROM my_table a
  INNER  join (select id,   
            max(b.status) lstatus 
            from my_table b 

              group by id)  t on t.id = a.id and 

仅限数值

  SELECT a.*, b.status as t.lstatus
  FROM my_table a
  INNER  join (select id,   
            max(b.status) lstatus 
            from my_table b 
            where IsNumeric([b.status])=True
              group by id)  t on t.id = a.id and 

答案 1 :(得分:0)

您可以尝试使用sudo systemctl status httpdevice.service ● httpdevice.service - httpdevice Loaded: loaded (/lib/systemd/system/httpdevice.service; enabled) Active: inactive (dead) since Fri 2018-04-27 18:01:52 CEST; 17min ago Process: 402 ExecStart=/home/pi/update.sh (code=exited, status=0/SUCCESS) Main PID: 402 (code=exited, status=0/SUCCESS) Apr 27 18:01:51 raspberrypi systemd[1]: Starting httpdevice... Apr 27 18:01:51 raspberrypi systemd[1]: Started httpdevice. 为seq排序的ID中的每一行指定编号。将其加入到您的id匹配的表和rownumber ROW_NUMBER() = 1。

<强> DEMO

rn

答案 2 :(得分:0)

尝试以下内容。

with status as (
Select distinct(id),status from table order by seq desc)select a.*,s.status as LStatus from table a,status s where a.id=s.id;

答案 3 :(得分:0)

使用可以在此使用subquery

select *, 
       (select top 1 Status from table where id = t.id order by status desc) as Lstatus 
from table t;