SQL内部联接使用Distinct和Order by Desc

时间:2015-03-27 17:00:49

标签: sql sql-server sql-server-2008

表p。 Table a 表b。 enter image description here我有两张桌子。表A有超过8000条记录,并且随着时间的推移不断增长。 表B只有5个左右的记录并且很少增长但有时会增长。

我想查询表A的表A的ID与表B匹配的最后记录。问题是;我从表A中获取了所有行。我只需要表A和B匹配一次的那些行。当新行插入表B并且永远不会重复时,这些是唯一的ID。

非常感谢任何帮助。

SELECT a.nshift, 
       a.loeeworkcellid, 
       b.loeeconfigworkcellid, 
       b.loeescheduleid, 
       b.sdescription, 
       b.sshortname 
FROM   oeeworkcell a 
       INNER JOIN dbo.oeeconfigworkcell b 
               ON a.loeeconfigworkcellid = b.loeeconfigworkcellid 
ORDER  BY a.loeeworkcellid DESC 

2 个答案:

答案 0 :(得分:2)

我假设您希望获得lastest中唯一的TableA(如您所说)行但JOIN为您提供所有行。您可以使用{{3获取rownumber然后应用连接并使用Where子句对其进行过滤,以仅选择JOIN中的第一行。那你可以尝试如下,

;WITH CTE 
AS
(
   SELECT * , ROW_NUMBER() OVER(PARTITION BY loeeconfigworkcellid  ORDER BY loeeworkcellid desc) AS Rn
   FROM oeeworkcell 
)


SELECT a.nshift, 
       a.loeeworkcellid, 
       b.loeecoonfigworkcellid, 
       b.loeescheduleid, 
       b.sdescription, 
       b.sshortname 
FROM   CTE a 
       INNER JOIN dbo.oeeconfigworkcell b 
               ON a.loeeconfigworkcellid = b.loeeconfigworkcellid 
WHERE
    a.Rn = 1

答案 1 :(得分:1)

您需要按数据分组,只选择条件为min id的数据。

SELECT a.nshift, 
       a.loeeworkcellid, 
       b.loeecoonfigworkcellid, 
       b.loeescheduleid, 
       b.sdescription, 
       b.sshortname 
FROM   oeeworkcell a 
INNER JOIN dbo.oeeconfigworkcell b 
ON a.loeeconfigworkcellid = b.loeeconfigworkcellid 
group by 
a.nshift, 
       a.loeeworkcellid, 
       b.loeecoonfigworkcellid, 
       b.loeescheduleid, 
       b.sdescription, 
       b.sshortname 
having a.loeeworkcellid = min(a.loeeworkcellid)