小编典典

连接两个MSSQL表(唯一值)

sql

我要加入的SQL Server数据库中有两个表:

人物表:

PersonId   Name    DeviceId
001        John    11111
002        Eric    22222
003        Steve   33333

设备表:

DeviceId  Date
11111     2013-02-01
11111     2013-02-02
11111     2013-02-03
22222     2013-02-03
22222     2013-02-01

我想要的结果如下

PersonId   Name   DeviceId  Date         IsRegistered
001        John   11111     2013-02-03       1
002        Eric   22222     2013-02-03       1
003        Steve  33333     null             0

如您所见,我想要表之间的联接,而我只想要唯一的值。数据字段应为最后注册的(最新日期)。如果此人在日期字段中IsRegistered具有值,则应具有值0

如果有人知道我可以解决这个问题,我将不胜感激


阅读 173

收藏
2021-04-22

共1个答案

小编典典

询问:

SELECT 
  p.*, d.maxdate
FROM persons p
left join
(  SELECT id, MAX(date) MaxDate
   FROM device   
   GROUP BY id
) d  ON p.deviceid = d.id
     ORDER BY d.maxdate DESC;



| PERSONID |  NAME | DEVICEID |                         MAXDATE |
-----------------------------------------------------------------
|        1 |  John |    11111 | February, 03 2013 02:00:00+0000 |
|        2 |  Eric |    22222 | February, 03 2013 00:00:00+0000 |
|        3 | Steve |    33333 |                          (null) |

我看到您也需要isRegistered专栏,这里是:

  • SQLFIDDLE WITH最后一列

询问:

SELECT 
    p.*, d.maxdate, case when d.maxdate is null then 0 else 1 end as isRegistered
    FROM persons p
    left join
    (  SELECT id, MAX(date) MaxDate
       FROM device   
       GROUP BY id
    ) d  ON p.deviceid = d.id
         ORDER BY d.maxdate DESC
    ;

结果:

| PERSONID |  NAME | DEVICEID |                         MAXDATE | ISREGISTERED |
--------------------------------------------------------------------------------
|        1 |  John |    11111 | February, 03 2013 02:00:00+0000 |            1 |
|        2 |  Eric |    22222 | February, 03 2013 00:00:00+0000 |            1 |
|        3 | Steve |    33333 |                          (null) |            0 |
2021-04-22