用where和MAX加入2个表

时间:2016-11-09 10:37:59

标签: sql sql-server join sql-server-2005 max

我有2张桌子;

TableSN

snID SerialNR Unit Version
 1    123     A      A1
 2    456     A      A2

TableDelivery

dID SerialNR Team
 1    456      US
 2    456      GE
 3    456      FI

结果

snID   SerialNR   Unit   Version  Team
 1       123       A       A1
 2       456       A       A2      FI

我需要根据TableSN and SerialNR获取表格,列出版本的位置。在同一个表格中,我需要显示Team-column的最新输入data (= MAX(dID))。当有团队数据可用时,我能够正确显示表格。

我的查询就像这样

SELECT TableSN.snID, TableSN.SerialNR, TableSN.Unit, TableSN.Version, TableDelivery.Team
FROM TableSN 
     LEFT OUTER JOIN TableDelivery ON TableDelivery. SerialNR = TableSN. SerialNR 
     LEFT OUTER JOIN ( 
         SELECT SerialNR, MAX(dID) AS snRank
         FROM TableDelivery AS TableDelivery _1
         GROUP BY SerialNR
     ) AS NewTeam ON TableDelivery. SerialNR = NewTeam. SerialNR AND TableDelivery.dID = NewTeam.snRank
WHERE (TableSN.Version = @Version)

如果没有可用的团队,如何才能看到SerialNR

感谢您的指导和支持。

这就是所需要的:

[enter image description here]

3 个答案:

答案 0 :(得分:0)

  DECLARE @Version VARCHAR(5)
SET @Version = 'A1'

     SELECT Ts.snID,ts.SerialNR,ts.Unit,ts.Version,TD.Team FROM @TableSN ts left join @TableDelivery td ON ts.SerialNR = td.SerialNR
     WHERE ts.Version = @Version

     UNION 

     SELECT Ts.snID,ts.SerialNR,ts.Unit,ts.Version,TD.Team FROM @TableDelivery TD left join @TableSN TS ON TD.SerialNR = ts.SerialNR
     WHERE dID = (SELECT MAX(dID) FROM @TableDelivery) 

    **output**

    snID    SerialNR    Unit    Version Team
    1        123         A        A1    NULL
    2        456         A        A2    FI

答案 1 :(得分:0)

您需要在sql中包含null条件,如下所示:

SELECT TableSN.snID, TableSN.SerialNR, TableSN.Unit, TableSN.Version, TableDelivery.Team
FROM TableSN 
LEFT OUTER JOIN TableDelivery ON TableDelivery. SerialNR = TableSN. SerialNR 
LEFT OUTER JOIN (SELECT SerialNR, MAX(dID) AS snRank
                    FROM TableDelivery AS TableDelivery _1
                    GROUP BY SerialNR) AS NewTeam ON (TableDelivery. SerialNR = NewTeam. SerialNR 
                    OR (TableDelivery. SerialNR IS NULL AND NewTeam. SerialNR IS NULL))
                    AND TableDelivery.dID = NewTeam.snRank
WHERE (TableSN.Version = @Version)

答案 2 :(得分:0)

试试这个:

SELECT TableSN.snID, TableSN.SerialNR, TableSN.Unit, TableSN.Version, TableDelivery.Team
FROM TableSN 
LEFT JOIN TableDelivery ON TableDelivery.SerialNR = TableSN. SerialNR AND 
                           TableDelivery.dID = (SELECT MAX(dID) 
                                                FROM TableDelivery AS t         
                                                WHERE t.SerialNR = TableSN. SerialNR)
WHERE (TableSN.Version = @Version)